循环用户输入直到满足条件 [英] Loop user input until conditions met

查看:238
本文介绍了循环用户输入直到满足条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to ask the user to input a number to be used as the start of a range, and then input another number that is the end of the range. The start number has to be 0 or greater and the end number cannot be larger than 1000. Both numbers must be divisible by 10. I have found a way to meet these conditions, however if they are not met my program just tells the user that their input was incorrect. Is it possible for me to code it so that after the user inputs it will check to make sure the conditions are met, and if they are not loop back and make them input again. Here is the code I have so far.

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


推荐答案

轻松与do-while:

Easy with 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

这篇关于循环用户输入直到满足条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆