我正在使用scanner
方法NextInt()
和NextLine()
读取输入。
它看起来是这样的:
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
System.out.println("Enter 1st string");
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
问题是,输入数值后,跳过第一个input.NextLine()
,执行第二个input.NextLine()
,这样我的输出就像这样:
Enter numerical value
3 // This is my input
Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped
Enter 2nd string // ...and this line is executed and waits for my input
我测试了我的应用程序,看起来问题在于使用input.nextInt()
。 如果删除它,那么string1=input.NextLine()
和string2=input.NextLine()
都将按我希望的方式执行。
这是因为scanner.NextInt
方法不读取通过单击“Enter”创建的输入中的换行符,因此对scanner.NextLine
的调用在读取该换行符后返回。
当您在scanner.nextLine
之后使用scanner.nextLine
或任何scanner.nextfoo
方法(除了nextLine
本身)时,您将遇到类似的行为。
解决方法:
>
在每个scanner.NextLine
或scanner.NextFoo
之后调用scanner.NextLine
,以使用该行的其余部分,包括换行
int option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();
或者,更好的方法是通过scanner.nextLine
读取输入,并将输入转换为所需的适当格式。 例如,可以使用integer.ParseInt(String)
方法转换为整数。
int option = 0;
try {
option = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String str1 = input.nextLine();
问题出在input.nextInt()方法上--它只读取int值。 因此,当您继续使用input.nextline()读取时,您将收到“\n”Enter键。 所以要跳过这个,必须添加input.nextline()。 希望现在能搞清楚。
试试看:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
这是因为当您输入一个数字,然后按enter时,input.NextInt()
只使用该数字,而不使用“行尾”。 当input.NextLine()
执行时,它会消耗从第一个输入开始仍在缓冲区中的“行尾”。
相反,在input.NextInt()
之后立即使用input.NextLine()