繁体   English   中英

具有不同输入类型的连续嵌套扫描器,包括带空格的字符串

[英]Consecutive nested Scanners with different input types including a string with spaces

如果我有多个Scanner用户输入,Scanner如何读取带空格的整个字符串? 虽然我看到有多个答案建议使用Scanner.nextLine() ,但我不想输入整数作为choice ,而在同一行输入String phrase (这就是为什么我使用switch, case而不是if/elseint choice = in.nextInt()

public static void main (String[] args){
Scanner in = new Scanner(System.in);
System.out.println ("welcome to November 1st Homework choices! if you would like to test the SSN condenser, input 1! if you would like to test the 'a' counter, input 2! If you would like to test both, enter 3!");
int choice = in.nextInt();
switch(choice){
  ...
  case 2:
     System.out.println("Please input a phrase of any sort to count the number of 'a''s in the phrase! :)");
     String phrase = in.next();
     System.out.println("The number of 'a's in the phrase is " + CountA(phrase));
    break;
  case 3:
    ...
    System.out.println("Please input a phrase of any sort to count the number of 'a''s in the phrase! :)");
    String phrase2 = in.next();
    System.out.println("The number of 'a's in the phrase is " + CountA(phrase2));
    break;
  default:
    System.out.println("YOU MUST ENTER A NUMBER BETWEEN 1 AND 3!! >:(D--");
    break;
}

}

我希望我把问题弄清楚了,我很困惑。

使用String phrase = in.nextLine(); 这是2个输出

出现此问题的原因是,当您按Enter键时,会创建一个“不可见”换行符,并且该字符不会被初次使用nextLine()之外的其他任何扫描程序方法拾取。 您可以在此处了解更多信息。

假设您输入3,然后按Enter。 扫描程序队列如下所示:

"3\n"

然后使用in.next(); 扫描程序获取数字,但保留新行char:

"\n"

因此,当您到达String phrase = in.next(); 它将以该新行char作为输入。

解决方案是使用nextLine()捕获它,而不对其执行任何操作。 因此,在您的代码中,它看起来像:

int choice = in.nextInt();
in.nextLine(); //catch new line char

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM