gpt4 book ai didi

Java 扫描器跳过输入 nextLine() 但不跳过 next()

转载 作者:行者123 更新时间:2023-12-04 10:38:42 26 4
gpt4 key购买 nike

<分区>

我在 Java 扫描器获取用户输入时遇到了一个相当奇怪的问题。我制作了一个练习程序,首先使用 nextDouble() 读取 double ,输出一些琐碎的文本,然后使用相同的扫描器对象通过 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()

它也有效

所以我的问题是为什么我的 Scanner 对象不要求我提供新的输入?如果我打印出“input2”的值,它是空的。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com