System.out.println("Enter number of dice to throw, an integer [2, 10]: ");
Scanner keyboard = new Scanner (System.in);
n = keyboard.nextInt();
//if the input is valid
if (n>1 && n<11)
{`
System.out.println("good");
Random rn = new Random();
int random = rn.nextInt((6-1) +1) +1;
System.out.println("random number is " + random);
}
else
{
//if the users input is invalid
while (n<2 && n>10)
{
System.out.println("error, must be in [2,10] ");
n = keyboard.nextInt();
}
}
您的逻辑不正确。数量n
不能小于2
并且永远不能大于10
。您需要小于2
或大于10
。使用||
而不是&&
。
while (n<2 || n>10)
如果不满足"If"语句中的条件,那么程序默认情况下不会转到"else"语句吗?那么,你甚至需要while语句吗?
实际上它确实输入了'else',但不在'while'内部。因为n不能是<2和>10。
更换
while (n<2 && n>10)
带
while (n<2 || n>10)