JAVA:关于nextLine()的一个小细节

来源:

JAVA PRACTICE|HackerRank

原题:

In this challenge, you must read an integer, a double, and a String from stdin, then print the values according to the instructions in the Output Format section below. To make the problem a little easier, a portion of the code is provided for you in the editor.

Input Format
There are three lines of input:
The first line contains an integer.
The second line contains a double.
The third line contains a String.

Output Format
There are three lines of output:
On the first line, print String: followed by the unaltered String read from stdin.
On the second line, print Double: followed by the unaltered double read from stdin.
On the third line, print Int: followed by the unaltered integer read from stdin.

Sample Input

42
3.1415
Welcome to HackerRank's Java tutorials!

Sample Output

String: Welcome to HackerRank's Java tutorials!
Double: 3.1415
Int: 42

代码块(原答案)

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        double d = scan.nextDouble();
        String s = scan.nextLine();
        

        // Write your code here.

        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

*这道题很有意思,在int整数值被输入之后输入字符串的时候,原本打算用的是上面的方法,结果输出的是

String:
Double: 3.1415
Int: 42

为什么呢?来看一下题目给的提醒。

Note: If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).

原来是因为在Scanner类读取了Int整数值之后,nextInt()是不读取整数值后面的空格的,因此就把一个enter换行符留在了屁股后面没有读取。
但是!!scan.nextLine()的作用是以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符,在这题中,也就是一个空格!没有读取任何整数值。

因此这道题正确的解法应该是:

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        double d = scan.nextDouble();
        scan.nextLine(); //把int后面的换行符读掉
        String s = scan.nextLine(); 
        

        // Write your code here.

        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容