为什么扫描仪输入不起作用?

时间:2015-06-18 23:19:01

标签: java

所以我是一名新的Java程序员,我想弄清楚为什么一段代码不起作用。我遇到的问题是:“String interests = input.nextLine();”,它跳过用户的输入并跳转到下一个System.out,所以它只是在控制台中显示“你的个人资料......”在允许用户输入任何数据之前。对不起,如果这是一个愚蠢的问题,我很新!

System.out.println("Hello, " + name + "! What is your gender?");
String gender = input.nextLine();
System.out.println("Okay, " + name + ", you are a " + gender + ". Now, tell me, what is your age?");
int age = input.nextInt();
System.out.println("Great! We're almost done. What are three interests you have?");
String interests = input.nextLine();

System.out.println("...Your profile...");
System.out.println("Name: " + name);
System.out.println("Gender: " + gender);

5 个答案:

答案 0 :(得分:0)

尝试改为  。System.console()的readLine();

答案 1 :(得分:0)

请说明您如何声明Scanner

仅供参考,以这种方式完成。

Scanner sc = new Scanner(System.in);
...
System.out.println("Hello, " + name + "! What is your gender?");
String gender = input.nextLine();
...

答案 2 :(得分:0)

我假设当您申报扫描仪时,您没有Scanner input = new Scanner(System.in),当您使用扫描仪时,您需要将System.in放在括号中。所以它是 String gender = input.nextLine();

答案 3 :(得分:0)

这样说:

int age = input.nextInt();
input.nextLine();
System.out.println("Great! We're almost done. What are three interests you have?");
String interests = input.nextLine();

其余代码可能等于您上面的代码。

编辑:它必须是这样的(我的意思是,不将行存储在任何变量中),因为nextInt()函数不读取整行,只是下一个整数。因此,当nextInt()函数读取int时,Scanner的“光标”将位于int之后的位置。

例如,如果您在尝试阅读int时放置了多个单词(以空格分隔),则在您的兴趣变量中,您将阅读{{1}的其余部分。之前无法阅读。所以,如果你有:

nextInt()

现在你将存储:

System.out.println("Okay, " + name + ", you are a " + gender + ". Now, tell me, what is your age?");
//Here you enter --> 18 This is a prove
int age = input.nextInt();
System.out.println("Great! We're almost done. What are three interests you have?");
//Here you won't be able to put anything
String interests = input.nextLine();

但如果你把代码放在这样:

age = 18;
interests = "This is a prove";

现在你将拥有的价值是:

System.out.println("Okay, " + name + ", you are a " + gender + ". Now, tell me, what is your age?");
//Here you enter --> 18 This is a prove
int age = input.nextInt();
input.nextLine();
//Now the Scanner go to a new line (because of the nextLine) but without storing the value
System.out.println("Great! We're almost done. What are three interests you have?");
//Now you are in a new line and you are going to be able to write. For example --> I am reading this.
String interests = input.nextLine();

所以,总而言之,如果你有一个age = 18; interests = "I am reading this."; 并且你正在尝试阅读一个nextInt(),你会读到它,但是光标将保持在这一行的最后,你赢了'能够阅读下一行。为此,您必须阅读整行,而不用int存储它。

我希望它会对你有所帮助!

答案 4 :(得分:0)

您:

String interests = input.nextLine();

因为没有结束而被跳过,请查看here以获取更多信息,您可以尝试仅使用nextLine()重新设置所有next()