循环用户输入直到满足条件

时间:2013-04-05 20:42:07

标签: java

我需要让用户输入一个数字作为范围的开头,然后输入另一个数字作为范围的结尾。起始编号必须为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");
    }

3 个答案:

答案 0 :(得分:6)

轻松做事:

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

答案 1 :(得分:3)

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

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

应该这样做。

答案 2 :(得分:0)

通用程序是:

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

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