我试图将键盘输入变成整数,但是我的程序不断崩溃。 当输入了诸如“ k”之类的字符时,它可以工作,但是当我输入“ 5”时,则崩溃。 关于我在做什么错的任何想法吗?
// Getting an integer value.
public static int getInt() {
int numberEntered = 0;
String entry = "";
Scanner keyboard = new Scanner(System.in);
while (!keyboard.hasNextInt()) {
entry = keyboard.next();
System.out.println("That is not an integer. " + "Please try again.");
}
numberEntered = Integer.parseInt(entry);
System.out.print(numberEntered);
return numberEntered;
}
输出:
Error given: k That is not an integer.
Please try again.
8
Exception in thread "main" java.lang.NumberFormatException: For input string: "k" at
java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Program2.getInt(Program2.java:56)
at Program2.problemSelectionMenu(Program2.java:40)
at Program2.main(Program2.java:14)
答案 0 :(得分:2)
您检查以确保输入具有下一个int,但是一旦Scanner
具有下一个int时,就永远不会将int解析为entry
,因此它仍然是错误的输入。您需要将用户输入的int
分配给entry
。您只需拨打nextInt()
:
while (!keyboard.hasNextInt()) {
entry = keyboard.next();
System.out.println("That is not an integer. " + "Please try again.");
}
numberEntered = keyboard.nextInt();
System.out.print(numberEntered);
return numberEntered;
答案 1 :(得分:1)
当您提供字符作为输入时,虽然循环条件为true,所以它进入while循环并扫描字符和字符的打印值,但是当您提供整数时,in while循环条件变为false并且不会进入while循环。在while循环之外,您正在解析整数,您不需要这样做,因为您将整数作为输入。您所要做的就是在 integer.parseInt(entry),您必须扫描整数,即 int我= keyboard.nextInt(); 因为在while循环条件下,您仅检查给定的输入是否为整数。但是如果是整数,您还没有扫描输入。
尝试一下!
int numberEntered = 0;
String entry = "";
Scanner keyboard = new Scanner(System.in);
while (!keyboard.hasNextInt()) {
entry = keyboard.next();
System.out.println("That is not an integer. " +"Please try again.");
}
numberEntered = keyboard.nextInt();
System.out.print(numberEntered);