提问人:Student 提问时间:4/6/2013 更新时间:10/1/2015 访问量:43232
循环用户输入,直到满足条件
Loop user input until conditions met
问:
我需要要求用户输入一个数字作为范围的开始,然后输入另一个数字作为范围的结束。起始数字必须大于或大于 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");
}
答:
7赞
Bernhard Barker
4/6/2013
#1
轻松完成:
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
评论
0赞
Student
4/6/2013
只是一个快速的后续问题,while 语句中的 (!good) 到底在说什么?虽然好=原始价值?
0赞
Bernhard Barker
4/6/2013
good
手段和手段(但通常是不好的做法)。good == true
!good
good == false
== boolean condition
0赞
user3932000
10/19/2016
这让我一直对这个声明感到不满。IllegalStateException
nextInt()
3赞
Ray Stojonic
4/6/2013
#2
你需要使用一段时间,比如:
while conditionsMet is false
// gather input and verify
if user input valid then
conditionsMet = true;
end loop
应该这样做。
评论
0赞
Bernhard Barker
4/6/2013
我建议使代码更接近 Java - , , no 和 no 。 和可选。while (!conditionsMet)
if (/*user input valid*/)
then
end loop
{
}
0赞
Boann
9/29/2015
#3
通用程序是:
- 在无限循环中读取输入。
- 使用
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));
评论