帮助处理问题。使用do{}while() 循环编写了一个带有输入验证的控制台菜单; 但是只有在第二次输入之后才处理输入 - 我不知道出了什么问题......
public class Menu {
public static void items() {
String[] menuArray = {
"Non-paired values 1-20", // 0
"Non-paired values 0-99 and 99-0", // 1
"Array with random values 0-9", // 2
"Array with random values 0-999 + print MIN/MAX", // 3
"Multi Array 8x5 with random values 10-99", // 4
"Multi Array 8x5 with MATRIX Format", // 5
"Loop counter", // 6
"Exit", // 7
"Choose your Menu item #>"}; // 8
for (int i = 0; i < menuArray.length; i++) {
if (i < menuArray.length - 2) {
System.out.println((i + 1) + ". " + menuArray[i]);
}
if ((i >= menuArray.length - 2) && (i < menuArray.length - 1)) {
System.out.print("Type \'" + menuArray[i] + "\' to exit program!\n");
}
if ((i >= menuArray.length - 1) && (i < menuArray.length)) {
System.out.print(STAR_LINE + menuArray[i]);
}
}
}}
-----------------------------------
public static void main(String[] args) {
boolean isExit = false;
do {
Menu.items();
Scanner scanner = new Scanner(System.in);
if (scanner.nextLine().isEmpty()) {
System.out.println("You didn't enter anything. Repeat please!");
} else {
if (scanner.hasNextInt()) {
int input = scanner.nextInt();
if ((input <= 0) || (input > 3)) {
System.out.println("Choose item from 1-3");
} else {
switch (input) {
case 1:
System.out.println("Entered number 1.\n");
break;
case 2:
System.out.println("Entered number 2.\n");
break;
case 3:
System.out.println("Entered number 3.\n");
break;
}
}
} else {
String inputString=scanner.nextLine();
if (inputString.equals("exit")) {
isExit = true;
}else {
System.out.println("You entered STRING, please read menu instruction");
}
}
}
}while (!isExit);
}
因为您正在使用您输入的内容从输入中删除一整行:
做
然后在这里清除空输入: