循环用户输入,直到满足条件
我需要让用户输入一个数字以用作范围的开始,然后输入另一个数字作为范围的结束。起始编号必须为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");
}
回答:
轻松做:
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
以上是 循环用户输入,直到满足条件 的全部内容, 来源链接: utcz.com/qa/405362.html