(Java)nextLine()在运行时跳过,同时在之前工作 [英] (Java) nextLine() skipped in runtime, while working previously

查看:77
本文介绍了(Java)nextLine()在运行时跳过,同时在之前工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的java程序的一部分中,我为用户读取了一系列输入。

In part of my java program I read a sequence of inputs for the user.

Scanner in = new Scanner(System.in);
System.out.println();
System.out.print("Enter student name: ");
String nameParameter = in.nextLine();
System.out.print("Enter student number: ");
int studentNoParameter = in.nextInt();
System.out.print("Enter subject: ");
String subjectParameter = in.nextLine();
System.out.print("Enter level: ");
int levelParameter = in.nextInt();
int[] resultsParameter;
resultsParameter = new int[3];
System.out.println("Enter results (0 if not taken yet)...");
System.out.print("First year: ");
resultsParameter[0] = in.nextInt();
System.out.print("Second year: ");
resultsParameter[1] = in.nextInt();
System.out.print("Third year: ");
resultsParameter[2] = in.nextInt();
System.out.println();

程序编译,但行:

String subjectParameter = in.nextLine();

在运行时似乎被跳过。

而不是我的输出:

输入主题:[用户输入]

Enter Subject: [User Input]

输入等级:[用户输入]

Enter Level: [User Input]

它出现为:

输入主题:输入等级:[用户输入]

Enter Subject: Enter Level: [User Input]

以下输入分配给levelParameter,如果输入的不是整数,则会产生错误,因此似乎只是跳过了代码行。

The following input is assigned to levelParameter, and an error results if you input something other than an integer, so it seems that the line of code has simply been skipped.

我非常喜欢java新手而且我很困惑。我知道这最终会变得非常简单和愚蠢。提前感谢您的时间。

I'm very much a java novice and I'm rather confused. I know this is going to turn out to be something really simple and silly in the end though. Thank you in advance for your time.

推荐答案

那是因为在读完int后,该行的其余部分(为空)仍然未读,下一次读取nextline()的调用将读取空行。

That's because after reading the int, the rest of the line (which is empty) is still unread and the next call to read nextline() will read the empty line.

所以当

int studentNoParameter = in.nextInt(); 

执行

,输入int并按Enter键,这会创建一个'\ n'作为输入。
下一个电话:

is executed, you enter the int and you hit enter, which creates a '\n' as input. The next call:

in.nextLine(); 

继续读取int之后的其余行,这是空的,它遇到'\\ \\ n'并终止。

continues to read the rest of the line after the int, which is empty, and it encounters '\n' and terminates.

这篇关于(Java)nextLine()在运行时跳过,同时在之前工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆