如果我有多个扫描仪用户输入,扫描仪如何读取带有空格的整个字符串?虽然我已经看到多个答案建议使用Scanner.nextLine()
,但我不想在同一行上输入choice
的整数和字符串phrase
(这就是为什么我使用 switch, case
而不是 if/else
) int 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 并按回车键。扫描程序队列将如下所示:
"3n"
然后你使用in.next();
.扫描仪获取数字,但保留新行字符:
"n"
所以当你到达你的String phrase = in.next();
.它将采用该新行字符作为输入。
解决方案是用nextLine()
抓住它,不要对它做任何事情。所以在你的代码中,它看起来像:
int choice = in.nextInt();
in.nextLine(); //catch new line char