Java扫描程序跳过输入nextLine(),但不跳过next()
我在Java扫描器获取用户输入时遇到了一个相当奇怪的问题。我制作了一个练习程序,首先使用Java扫描程序跳过输入nextLine(),但不跳过next(),java,java.util.scanner,user-input,Java,Java.util.scanner,User Input,我在Java扫描器获取用户输入时遇到了一个相当奇怪的问题。我制作了一个练习程序,首先使用nextDouble()读取一个double,输出一些简单的文本,然后使用同一个scanner对象使用nextLine()获取字符串输入 代码如下: import java.util.Scanner; public class UsrInput { public static void main(String[] args) { //example with user double
nextDouble()
读取一个double,输出一些简单的文本,然后使用同一个scanner对象使用nextLine()
获取字符串输入
代码如下:
import java.util.Scanner;
public class UsrInput {
public static void main(String[] args) {
//example with user double input
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number: ");
double input = reader.nextDouble();
if(input % 2 == 0){
System.out.println("The input was even");
}else if(input % 2 == 1){
System.out.println("The input was odd");
}else{
System.out.println("The input was not an integer");
}
//example with user string input
System.out.println("Verify by typing the word 'FooBar': ");
String input2 = reader.nextLine();
System.out.println("The string equal 'FooBar': " + input2.equals("FooBar"));
}
}
很明显,我的目的是请求第二次输入,并打印字符串input2是否等于'FooBar'。然而,当我运行这个函数时,它跳过了第二个输入,并立即告诉我它不相等但是如果我将reader.nextLine()
更改为reader.next()
它会突然工作
如果我创建一个新的Scanner实例并使用reader2.nextLine()
所以我的问题是为什么我的扫描器对象不向我请求新的输入?如果我打印出“input2”的值,它是空的。您必须清除扫描仪,才能使用
reader.nextLine()代码>,如下所示:
if (input % 2 == 0) {
System.out.println("The input was even");
} else if (input % 2 == 1) {
System.out.println("The input was odd");
} else {
System.out.println("The input was not an integer");
}
reader.nextLine();//<<--------------Clear your Scanner so you can read the next input
//example with user string input
System.out.println("Verify by typing the word 'FooBar': ");
String input2 = reader.nextLine();
System.out.println("The string equal 'FooBar': " + input2.equals("FooBar"));
输出
Hello
World!
Hello
Java!
Hello World!
Hello Java!
输出
Hello
World!
Hello
Java!
Hello World!
Hello Java!
因此我们可以理解,next()
逐字阅读,这样它就不会像nextLine()
那样使用,这确实是同一个问题(我在搜索中找不到它),但这仍然让我想知道,为什么nextDouble()之后的nextLine()会出现问题,而next()不会出现问题?next()simlpy是否忽略缓冲区中的换行符>谢谢,这确实解决了我的问题,而且我的问题似乎已经在别处被问到和回答了。这给我留下了一个问题:为什么“next()”忽略了\n仍然留在扫描仪中的内容?@Dr.hoeniker next逐字阅读,并用空格分隔,不像它使用的nextLine()\n在我的示例中您可以理解得更多好吧,这很有道理,next()同样忽略了空格和换行符,在我的示例中,忽略nextDouble()的\n左键并等待我的输入@Hoeniker博士更正不只是空格它可以是任何分隔符ok阅读我已经分享的链接你会了解更多