Java中nextInt()后紧跟nextLine()方法造成的一些问题

遇到的问题:

public class Test {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        String[] arr = new String[n];
        for (int i = 0; i < n; i++) {
            arr[i] =  sc.nextLine();
        }

        System.out.println(Arrays.toString(arr));
    }
}

先看这段代码,看上去很自然,n表示我们字符串数组的长度,for循环用于每个元素的输入,一般的同学们都会这样很自然地写。
我们运行后,在控制台如此输入:

3
a
b
c

你会发现,在输到b并按下回车时,还没等你输入c,控制台就输出结果了:

[, a, b]

这是为什么呢?
从表面来看输出结果,猜想应该是数组的第0个元素被系统写入了一个空字符或者转义字符之类的。
为了验证这个猜想我们在原来的程序中加一行代码:

public class Test {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        String[] arr = new String[n];
        for (int i = 0; i < n; i++) {
            arr[i] =  sc.nextLine();
        }
        System.out.println(arr[0]); // 输出首个元素看看
        System.out.println(Arrays.toString(arr));
    }
}

输入不变,输出为:


[, a, b]

我们可以看出,第一行有换行符,说明那个arr[0]其实就是\n


验证完了最后我们再去看看官方文档:

nextInt(): it only reads the int value, nextInt() places the cursor in
the same line after reading the input.(此方法只读取整型数值,并且在读取输入后把光标留在本行

扫描二维码关注公众号,回复: 2683800 查看本文章

next(): read the input only till the space. It can’t read two words
separated by space. Also, next() places the cursor in the same line
after reading the input.(读取输入直到遇见空格。此方法不能读取被空格分隔开的内容,并且在读取输入后把光标留在本行

nextLine(): reads input including space between the words (that is,
it reads till the end of line \n). Once the input is read, nextLine()
positions the cursor in the next line.(读取包括空格在内的输入,而且还会读取行尾的换行字符\n,读取完成后光标被放在下一行

如此一来,我们就非常清晰了,也就是说这个nextLine()方法如其名,会读取当前这一整行包括换行符。
每一次读取过程是从光标位置开始的。所以,一开始那个程序当我们输入3并按下回车,由于nextInt()方法只读取数值而不会读取换行符,所以光标停在了3和\n之间,然后for循环中的第一次nextLine()方法把3后面的换行符\n读取掉了,并把光标弹到下一行,这个时候才开始读取你输入的a字符。最后,才造成了arr[0]的内容其实是一个换行符。

所以我们为了正确地完成最初的输入,程序应该这样写:

public class Test {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine(); // 读掉数值后面的换行符
        String[] arr = new String[n];
        for (int i = 0; i < n; i++) {
            arr[i] =  sc.nextLine();
        }

        System.out.println(Arrays.toString(arr));
    }
}

猜你喜欢

转载自blog.csdn.net/ysy950803/article/details/78187893