问题描述
因为你实例input
是0
,但从来没有给用户一个机会来改变这种情况,前两个条件语句的条件总是假的(没有从扫描仪读取和0之间没有min
和max
)。因此,该程序会一直执行到else
每次。只需在之前添加一条语句,该语句将从用户do-
while
那里获取值input
。
input = scanner.nextInt();
// your do-while loop
(您可能还必须稍微调整代码以获得所需的交互类型。提示-您正在从用户读取两个值。)
解决方法
我目前正在创建第一个在控制台中执行的游戏。
我被要求验证可以用简单代码完成的输入。目标是输入,然后验证该数字是否为整数并且在1-4的范围内。如果可能,应使用基本算法解决该问题。
问题是它不会给我我想要的结果。当我输入字符串时,它可以工作,但是会在我输入的每个数字(包括范围内的数字)上循环播放。有人知道为什么吗?
public class Menu {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int input = 0;
int min = 1;
int max = 4;
boolean inputValidate;
System.out.println("Main Menu");
System.out.println("=========");
System.out.println("1. Play Game");
System.out.println("2. About");
System.out.println("3. View Saved Games");
System.out.println("4. Exit");
System.out.println("");
do {
System.out.print(">> ");
if (!scanner.hasNextInt()) {
inputValidate = false;
System.out.println("Not a number. Please input number 1-4.");
scanner.nextLine();
} else if (input <= max && !(input < min)) // if input <= 4 and input is not less than 1
{
input = scanner.nextInt();
inputValidate = true;
} else {
inputValidate = false;
System.out.println("Not in range. Please input number 1-4.");
scanner.nextLine();
}
} while (!(inputValidate));
switch (input) {
case 1:
break;
case 2:
System.out.println("Good work!");
break;
case 3:
break;
case 4:
break;
}
}
}
}