Scanner

遇到的问题:

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.(此方法只读取整型数值,并且在读取输入后把光标留在本行)

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));
    }
}

总结:
1.next()方法(next()、nextInt()、nextFloat()等等,除nextLine()外)一定要读取到有效字符之后才可以结束输入,有效字符之前遇到的空格、Tab键或Enter键等结束符会自动将其去掉,有效字符之后遇到的Enter键才将其视为结束符,所以next()方法不能得到带空格的字符串。结束读取后,光标不移动到下一行!!!
2.nextLine()方法,返回的是Enter键之前的所有字符,可以得到带空格的字符串。结束一行读取后,光标移到下一行!!!

  • 20
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值