public static int intInput(String prompt, String error) {
int intInput = 0; // Variable to be returned
// Start the scanner
Scanner keyboard = new Scanner(System.in);
// This loop check to make sure the user entered positive data
do {
System.out.println(prompt);
// This loop check if the user has entered an int
while (!keyboard.hasNextInt()) {
System.out.println(error);
keyboard.next();
}
intInput = keyboard.nextInt();
} while (intInput <= 0);
// Returns an int
return intInput;
}
如果用户在不输入任何数据的情况下按Enter键,则不会显示提示。它只会转到下一行,并且不会暗示用户仍可以输入数据。
我在nextLine旁边进行了更改,但仍然收到相同的错误
public static int intInput(String prompt, String error) {
int intInput = 0; // Variable to be returned
// Start the scanner
Scanner keyboard = new Scanner(System.in);
// This loop check to make sure the user entered positive data
do {
System.out.println(prompt);
// This loop check if the user has entered an int
while (!keyboard.hasNextInt()) {
System.out.println(error);
keyboard.nextLine();
}
intInput = keyboard.nextInt();
} while (intInput <= 0);
// Returns an int
return intInput;
}
好的,所以我通读了链接并尝试使用nextLine处理,但是它仍然没有改变
// Method for user int input
public static int intInput(String prompt, String error) {
int intInput = 0; // Variable to be returned
// Start the scanner
Scanner keyboard = new Scanner(System.in);
// This loop check to make sure the user entered positive data
do {
System.out.println(prompt);
// This loop check if the user has entered an int
while (!(keyboard.hasNextInt())) {
System.out.println(error);
keyboard.nextLine();
}
intInput = keyboard.nextInt();
keyboard.nextLine();
} while (intInput <= 0);
// Returns an int
return intInput;
}
答案 0 :(得分:0)
您可以在循环中放入try...catch
,如果用户未输入int
,则只捕获异常:
public static int intInput(String prompt, String error) {
int intInput = 0;
Scanner sc = new Scanner(System.in);
do {
try {
System.out.println("Enter an int");
intInput = Integer.parseInt(sc.nextLine());
} catch (Exception e) {
System.out.println(error);
intInput = 0;
}
} while (intInput == 0);
return intInput;
}
尽管您可能想进行一些适当的异常处理,但不能捕获通用的Exception
,但这更多是一个指导原则。通过在intInput
中将0
强制为catch
,这将意味着它将不会脱离do...while
并继续进行直到输入有效的int
为止。