在用户输入任何其他数据类型后,我需要输入正确的输入



我试图用Java制作一个菜单,并获得用户输入,直到用户输入正确的输入,所以我在代码中使用了while()。但当我运行代码时,唯一运行的是while loop,它会捕捉到错误,但它只是停留在那里。

这是我到目前为止的代码:

public static void main(String[] args) {
// calling void choice
choice();
// System.out.println("");
int choice = checkValidMenu();
while (choice != 0) {
// System.out.println("");
choice = input.nextInt();
if (choice == 1) {
System.out.println("Enter 1 to validate an integer: ");
choice = input.nextInt();
} // choice 1
else if (choice == 2) {
System.out.println("Enter 2 to validate a decimal number: ");
choice = input.nextInt();
} // choice 2
else if (choice == 3) {
System.out.println("Enter 3 to process an array: ");
choice = input.nextInt();
} // choice 3
else if (choice == 4) {
System.out.println("Enter 4 to process a file: ");
choice = input.nextInt();
} // choice
else if (choice == 5) {
System.out.println("Enter 5 to exit:");
choice = input.nextInt();
} // choice5
} // menu while
}// main
//method for choice
public static void choice() {
System.out.println("tMenu Options");
System.out.println("Enter 1 to validate an integer: ");
System.out.println("Enter 2 to validate a decimal choice: ");
System.out.println("Enter 3 to process an array: ");
System.out.println("Enter 4 to process a file");
System.out.println("Enter 5 to exit: ");
}// void method */
/// creating a method to validate user input
public static int checkValidMenu() {
try {
return input.nextInt();
} catch (InputMismatchException e) {
System.out.println("*** Invalid entry - Try again");
input.next();
return 0;
}
}
}// class

当您捕捉到错误时,您返回0,它被分配给"选择";。因此,您可以选择0进入while循环;也许在捕获无效条目时不应该返回0?我不确定我是否理解你的观点。

在主方法中,在while循环行之后注释choice=input.nextint()。不过,你可以添加更多的输入,让你的问题变得清晰。

public static void main(String[] args) {
// calling void choice
choice();

int choice = checkValidMenu();
while (choice != 0) {

//choice = input.nextInt();
if (choice == 1) {
System.out.println("Enter 1 to validate an integer: ");
choice = input.nextInt();
} 
else if (choice == 2) {
System.out.println("Enter 2 to validate a decimal number: ");
choice = input.nextInt();
} 
else if (choice == 3) {
System.out.println("Enter 3 to process an array: ");
choice = input.nextInt();
} 
else if (choice == 4) {
System.out.println("Enter 4 to process a file: ");
choice = input.nextInt();
} 
else if (choice == 5) {
System.out.println("Enter 5 to exit:");
choice = input.nextInt();
} 
} 
}

最新更新