0

我需要从 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();
}

}

}
4

2 回答 2

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();
}

然后您可以删除elsenow-removed 的部分if

于 2013-09-19T21:54:02.637 回答
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): ");
于 2013-09-19T22:17:38.250 回答