4

我需要让用户输入一个数字作为范围的开始,然后输入另一个数字作为范围的结束。起始数字必须为 0 或更大,结束数字不能大于 1000。两个数字都必须能被 10 整除。我找到了满足这些条件的方法,但是如果不满足这些条件,我的程序只会告诉用户他们的输入不正确。我是否可以对其进行编码,以便在用户输入后它会检查以确保满足条件,如果它们没有回送并再次输入。这是我到目前为止的代码。

    Scanner keyboard = new Scanner(System.in);
    int startr;
    int endr;
    System.out.println("Enter the Starting Number of the Range: ");
    startr=keyboard.nextInt();
    if(startr%10==0&&startr>=0){
        System.out.println("Enter the Ending Number of the Range: ");
        endr=keyboard.nextInt();
        if(endr%10==0&&endr<=1000){

        }else{
            System.out.println("Numbers is not divisible by 10");
        }
    }else{
        System.out.println("Numbers is not divisible by 10");
    }
4

3 回答 3

7

轻松使用do-while:

Scanner keyboard = new Scanner(System.in);
int startr, endr;
boolean good = false;
do
{
  System.out.println("Enter the Starting Number of the Range: ");
  startr = keyboard.nextInt();
  if(startr % 10 == 0 && startr >= 0)
    good = true;
  else
    System.out.println("Numbers is not divisible by 10");
}
while (!good);

good = false;
do
{
    System.out.println("Enter the Ending Number of the Range: ");
    endr = keyboard.nextInt();
    if(endr % 10 == 0 && endr <= 1000)
      good = true;
    else
      System.out.println("Numbers is not divisible by 10");
}
while (!good);

// do stuff
于 2013-04-05T20:45:53.973 回答
3

您需要使用一段时间,例如:

while conditionsMet is false
    // gather input and verify
    if user input valid then
        conditionsMet = true;
end loop

应该这样做。

于 2013-04-05T20:48:06.553 回答
0

通用程序是:

  1. 在无限循环中读取输入。
  2. break;满足条件时使用语句退出循环。

例子:

Scanner keyboard = new Scanner(System.in);
int startr, endr;

for (;;) {
    System.out.println("Enter the starting number of the range: ");
    startr = keyboard.nextInt();
    if (startr >= 0 && startr % 10 == 0) break;
    System.out.println("Number must be >= 0 and divisible by 10.");
}

for (;;) {
    System.out.println("Enter the ending number of the range: ");
    endr = keyboard.nextInt();
    if (endr <= 1000 && endr % 10 == 0) break;
    System.out.println("Number must be <= 1000 and divisible by 10.");
}

如果在无效输入后您只想显示错误消息而不重复初始提示消息,请将初始提示消息移动到循环上方/外部。

如果您不需要单独的错误消息,您可以重新安排代码以使用 do-while 循环来检查条件,这会更短一些:

Scanner keyboard = new Scanner(System.in);
int startr, endr;

do {
    System.out.println("Enter the starting number of the range.");
    System.out.println("Number must be >= 0 and divisible by 10: ");
    startr = keyboard.nextInt();
} while (!(startr >= 0 && startr % 10 == 0));

do {
    System.out.println("Enter the ending number of the range.");
    System.out.println("Number must be <= 1000 and divisible by 10: ");
    endr = keyboard.nextInt();
} while (!(endr <= 1000 && endr % 10 == 0));
于 2015-09-29T00:05:56.833 回答