我正在尝试让扫描仪循环接收输入。一旦用户想要完成,他就可以退出这个循环。我尝试了许多不同的方法来做到这一点,但总是存在一些问题。这是代码:
private void inputEntries() {
Scanner sc = new Scanner(System.in);
System.out.println("Continue?[Y/N]");
while (sc.hasNext() && (sc.nextLine().equalsIgnoreCase("y"))) {//change here
System.out.println("Enter first name");
String name = sc.nextLine();
System.out.println("Enter surname");
String surname = sc.nextLine();
System.out.println("Enter number");
int number = sc.nextInt();
Student student = new Student(name, surname, number);
students.add(student);
try {
addToFile(student);
} catch (Exception ex) {
Logger.getLogger(TextReader.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Continue?[Y/N]");
}
}
上面代码的问题,也发生在我尝试过的不同方法上,是当用户键入 Y 时,Scanner
将跳过第一个输入姓名,然后跳转到姓氏。如果用户键入 N,则循环正确停止。有人可以解释发生这种情况的原因,以及如何使用 Scanner
类来克服?
p.s:执行类似 while(sc.nextLine().equals("Y"))
的操作,将导致循环在第一次运行循环后获取用户输入之前终止。
最佳答案
这是因为您正在使用 Scanner#next
方法。如果您查看该方法的文档,它会返回读取的下一个标记。
因此,当您使用 next
方法读取用户输入时,它不会读取末尾的 newline
。然后由 while
循环内的 nextLine()
读取。因此,您的 firstName
包含一个 newline
而您却不知道。
因此,您应该在 while 中使用 nextLine()
而不是 next()
。
nextInt
的情况与此类似方法。它也不读取换行符。因此,您可以使用 readLine
来读取
,并使用 Integer.parseInt
将其转换为 int
。如果输入值无法转换为 int
,它会抛出 NumberFormatException
。所以你需要相应地处理它。
你可以试试下面的代码:-
Scanner sc = new Scanner(System.in);
System.out.println("Continue?[Y/N]");
while (sc.hasNext() && (sc.nextLine().equalsIgnoreCase("y"))) {//change here
System.out.println("Enter first name");
String name = sc.nextLine();
System.out.println("Enter surname");
String surname = sc.nextLine();
System.out.println("Enter number");
int number = 0;
try {
number = Integer.parseInt(sc.nextLine());
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
System.out.println("Continue?[Y/N]");
}
但是,请注意一件事,如果您输入的值无法传递给 Integer.parseInt
,您将得到一个异常,并且该输入将被跳过。对于这种情况,您需要使用 while
循环来处理它。
或者,如果您不想执行该异常处理:-
您可以在 sc.nextInt()
之后添加一个 empty sc.nextLine()
,这将消耗剩余的 newline
,例如这个:-
// Left over part of your while loop
String surname = sc.nextLine();
System.out.println("Enter number");
int number = sc.nextInt();
sc.nextLine(); // To consume the left over newline;
System.out.println("Continue?[Y/N]");
关于java - 使用扫描仪获取用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12999899/