这可能很简单,但我完全被难倒了。我需要帮助防止用户在do-while循环中输入字符串或空字符串。
以下代码
do {
int menuItem = input.nextInt();
switch (menuItem) {
case 1: System.out.println("------ You have selected choice [1] - Add a employee to collection ------ "); functions.addEmployee(); break;
case 2: System.out.println("------ You have selected choice [2] - Edit an employee details ------ "); functions.editEmployee(); break;
case 3: System.out.println("------ You have selected choice [3] - Delete an employee from collection ------ "); functions.deleteEmployee(); break;
case 4: System.out.println("------ You have selected choice [8] - Search employee by keyword ------ "); functions.EmpSearchByKeyword(); break;
default: System.out.println("Please enter in a valid integer to operate menu system (1-4)");
}
} while (input.hasNextInt());
答案 0 :(得分:0)
尝试使用while
循环而不是do-while
,如下所示:
while (input.hasNextInt()){
....//your code
}
答案 1 :(得分:0)
试试此代码
do {
while(true){
try{
int menuItem = input.nextInt();
break;
}catch(Exception e){
System.out.println("Error");
}
}
switch (menuItem) {
case 1: System.out.println("------ You have selected choice [1] - Add a employee to collection ------ "); functions.addEmployee(); break;
case 2: System.out.println("------ You have selected choice [2] - Edit an employee details ------ "); functions.editEmployee(); break;
case 3: System.out.println("------ You have selected choice [3] - Delete an employee from collection ------ "); functions.deleteEmployee(); break;
case 4: System.out.println("------ You have selected choice [8] - Search employee by keyword ------ "); functions.EmpSearchByKeyword(); break;
default: System.out.println("Please enter in a valid integer to operate menu system (1-4)");
}
} while (input.hasNextInt());