,如果你想繼續問,直到用戶鍵入一個有效的答案,或者只問一次,我無法理解。 while塊建議繼續詢問,直到輸入有效。 以下是您要求的小片段。我建議你閱讀一些書,在那裏有很多建議。
public static class InvalidUserException extends Exception {
public InvalidUserException(String message) {
super(message);
}
public InvalidUserException(String message, Throwable cause) {
super(message, cause);
}
}
private static int getIntFromScanner(int max) throws InvalidUserException {
int nextInt = 0;
Scanner sc = new Scanner(System.in);
try {
nextInt = sc.nextInt();
} catch (InputMismatchException e) {
throw new InvalidUserException("Input must be a valid Integer", e);
}
if (nextInt > max) {
throw new InvalidUserException(
"Input is bigger than allowed! Max: " + max + " Input: "
+ nextInt);
}
return nextInt;
}
public static int getUserOption(String prompt, int max) {
System.out.println(prompt);
do {
try {
return getIntFromScanner(max);
} catch (InvalidUserException e) {
System.out.println("Invalid option. Try again ("
+ e.getMessage() + ")");
}
} while (true);
}
public static void main(String[] args) {
int userOption = getUserOption("Gimme less than or equal 6!", 6);
System.out.println("You gave me " + userOption);
}
可以給你輸入嗎? –