我用if语句创建了我的代码,但如果他们输入的数字无效,我需要它重新提示用户输入一个数字

时间:2013-09-19 21:51:05

标签: java if-statement

我需要从2-24制作一个偶数个星号的盒子,并且如果输入了错误的号码则不知道如何重新提示。代码完美无缺,但它不会重新提升。我尝试在if语句的末尾使用continue语句,但我现在意识到它不会接受。有没有其他方法让它重新提升而不改变代码?

import java.util.Scanner;

public class Box
{
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.print("Enter an even number (2-24): ");
int line = input.nextInt();

if(line < 2 || line > 24 || line % 2 !=0)
    {
    System.out.println("Value must be an even number from 2-24");
 //THE PROBLEM IS THAT I NEED IT TO REPROMPT RIGHT HERE--HELP???
    }
else
{
int j=0;
while(j<line)
    {
    System.out.print("*");
    j++;// j=j+1
    }

System.out.println();       

int k=0;
while(k<line-2)
    {
    System.out.print("*");  
    int c=0;
    while(c<line-2)
        {
        System.out.print(" ");
        c++;
        }
    System.out.println("*");
    k++;
    }

int r=0;
while(r<line)
    {
    System.out.print("*");
    r++;// j=j+1
    }

System.out.println();
}

}

}

2 个答案:

答案 0 :(得分:4)

您需要将if语句更改为另一个while循环。它需要循环,而line值不可接受。确保在循环体内重新提示并重新接受输入:

int line = input.nextInt();

while (line < 2 || line > 24 || line % 2 !=0)
{
    System.out.println("Value must be an even number from 2-24");
    //THE PROBLEM IS THAT I NEED IT TO REPROMPT RIGHT HERE--HELP???
    System.out.print("Enter an even number (2-24): ");
    line = input.nextInt();
}

然后,您可以删除现已删除的else的{​​{1}}部分。

答案 1 :(得分:0)

作为好奇心,您可以将其作为一行for循环:

int n;
System.out.print("Enter an even number (2-24): ");
for (n = input.nextInt(); n < 2 || n > 24 || n % 2 !=0; n = input.nextInt())
    System.out.println("Value must be an even number from 2-24\nEnter an even number (2-24): ");