美文网首页Java
【Java】Scanner有关键盘字符混合输入

【Java】Scanner有关键盘字符混合输入

作者: Colleny_Z | 来源:发表于2018-07-17 17:08 被阅读24次
代码测试
        Scanner sc = new Scanner(System.in);
        System.out.println("NEXT--first");
        int i = sc.nextInt();
        System.out.println(i);
        
        System.out.println("NEXT--second");
        String s = sc.nextLine();
        //int j = sc.nextInt();
        System.out.println(s);

Console结果:

NEXT--first
1
1
NEXT--second

如果是正常的连续两个类型一致的字符,是没有任务问题的,但是混合输入这样是有误的,正如下述测试,还没有输入第二个字符,已经结束了。

文档解释

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,读取完成后光标被放在下一行

原因分析

  • 如果是两个数字连续输入,第一个输入完毕取出数字,遇\n结束,并继续输入第二个结束。
  • 如果是两个字符串输入,第一个输入完毕取出字符串,并取出后面的\n,光标移至下一行,同理完成第二个字符串的输入。
  • 如果是开始的测试代码这种情况,第一次输入数字,取出数字后,后面还有\n,但没有换行,当再进行第二次字符串输入时,直接将上次的\n取出,结束。故出现了开始的问题。

解决方案

  • 用同类型的字符接收,比如都用String;
  • 可创建多个Scannner分别接收
  • 在接收下一个字符前,可先执行sc.nextLine()取出上一次留下来的换行即可。





不积跬步,无以致千里

相关文章

网友评论

    本文标题:【Java】Scanner有关键盘字符混合输入

    本文链接:https://www.haomeiwen.com/subject/dudgpftx.html