试图让用户在 2 组值之间输入正确的整数,但例如,如果用户输入错误的整数,则 while 循环将跳过并运行到我程序中的下一个代码。如果有人能指出我如何让用户在每一步都弄错了问题,我将不胜感激。
System.out.print("How many asteroids: ");
int asteroid = input.nextInt();
while (asteroid > 0) {
System.out.print("x location of the asteroid (between 1-950 pixels): ");
double asteroidLocationX = input.nextDouble();
if (asteroidLocationX >= 1 && asteroidLocationX <= 950) {
System.out.print("y location of the asteroid (between 150-550 pixels): ");
double asteroidLocationY = input.nextDouble();
if (asteroidLocationY >= 150 && asteroidLocationY <= 550) {
System.out.print("Width of the asteroid (min: 30 pixels, max: 50 pixels): ");
double asteroidSizeWidth = input.nextDouble();
if (asteroidSizeWidth >= 30 && asteroidSizeWidth <= 50) {
System.out.print("Height of the asteroid (min: 30 pixels, max: 50 pixels): ");
double asteroidSizeHeight = input.nextDouble();
if (asteroidSizeHeight >= 30 && asteroidSizeHeight <= 50) {
gc.setFill(Color.ALICEBLUE);
gc.fillOval(asteroidLocationX, asteroidLocationY, asteroidSizeWidth, asteroidSizeHeight);
} else
System.out.println("Wrong input, try again");
} else
System.out.println("Wrong input, try again");
}else
System.out.println("Wrong input, try again");
} else
System.out.println("Wrong input, try again");
asteroid--;
}
答案 0 :(得分:1)
如果答案有问题,您需要重新提问
double val = -1;
do {
System.out.println("Enter a number between 1 and 10");
val = input.nextDouble();
while (input >= 1 && input <= 10);