Java代码实现If the user types something which is not an integer, the readPosInt method that you implemented in the previous question will automatically repeat the menu and ask the user to type an integer again until the user actually types an integer, so you do not have to worry about this in the code of the main method of your CLI class.
时间: 2023-06-15 14:04:23 浏览: 97
以下是Java代码实现该功能的示例:
```java
import java.util.Scanner;
public class CLI {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int choice = 0;
do {
System.out.println("Please choose an option:");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. Option 3");
System.out.println("4. Exit");
choice = readPosInt(); // 调用 readPosInt 方法读取用户输入的选项
switch (choice) {
case 1:
System.out.println("You chose Option 1");
break;
case 2:
System.out.println("You chose Option 2");
break;
case 3:
System.out.println("You chose Option 3");
break;
case 4:
System.out.println("Goodbye!");
break;
default:
System.out.println("Invalid option. Please choose again.");
}
} while (choice != 4);
}
private static int readPosInt() {
int num = 0;
while (true) {
try {
num = Integer.parseInt(scanner.nextLine());
if (num > 0) { // 确保输入的是正整数
break;
}
} catch (NumberFormatException e) {
// 用户输入了非整数,无需处理,直接重新循环提示用户输入
}
System.out.println("Invalid input. Please enter a positive integer.");
}
return num;
}
}
```
在上述代码中,我们使用了一个 do-while 循环来不断显示菜单,读取用户输入并执行相应操作,直到用户选择退出(输入 4)。在读取用户输入的过程中,我们调用了 readPosInt 方法来读取用户输入的选项,并确保输入的是正整数。如果用户输入了非整数,该方法会在循环中重新提示用户输入,直到用户输入一个合法的正整数为止。这样就可以保证程序不会因为用户的非法输入而崩溃。
阅读全文