使用 while 循环和 if 语句获取重复的用户输入
我想创建一个简单的程序,当猜到数字 2 或 3 时,该程序将终止,并且每当数字不在该范围内时,我希望弹出一条错误消息并说重试,然后我希望用户能够输入另一个数字,直到它们正确为止。
我尝试使用 if 语句,其中“n”大于或小于,但程序仍然无法正常工作。我让 while 循环条件为真,我希望这会重复该程序,这样我就可以再试一次,但没有这样的运气。 ''''
package meganImpasseProject;
import java.util.Scanner;
public class looping {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;
boolean correctChoice = true;
while(!correctChoice);
System.out.println("How many colours do you want?");
n = input.nextInt();
if(n<2) {
System.out.println("Invalid value, Please try again!");
n = input.nextInt();
}else if(n>3) {
System.out.println("Functionality currently not availible. Please try again");
n = input.nextInt();
}else {
System.out.println("Value OK");
}
}
System.exit(0);
''''
I am wanting to create a simple programme that will terminate when either the number 2 or 3 is guessed and whenever a number is not in that range I want an error message to pop up and say try again and then I want the user to be able to type in another number until it they are correct.
I have tried using if statements with my 'n' either being greater than or smaller than but the programme is still not working. I let the while loop condition be true and I expected this to repeat the programme so I could try again but no such luck.
''''
package meganImpasseProject;
import java.util.Scanner;
public class looping {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;
boolean correctChoice = true;
while(!correctChoice);
System.out.println("How many colours do you want?");
n = input.nextInt();
if(n<2) {
System.out.println("Invalid value, Please try again!");
n = input.nextInt();
}else if(n>3) {
System.out.println("Functionality currently not availible. Please try again");
n = input.nextInt();
}else {
System.out.println("Value OK");
}
}
System.exit(0);
''''
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的两个主要问题是:
首先,您的循环不包含任何实际操作,除了 noop
等于
第二个逻辑错误是您用
true
CorrectChoice 的值>,这样你的循环条件就永远不会满足并且循环永远不会进入。您应该将该值初始化为 false,然后在做出退出循环的正确选择后,在循环内将其更改为 true。
您的代码的更正版本看起来像这样:
还有更多可以改进的地方,例如捕获
InputMismatchException
来处理您的用户不输入数字而是输入普通文本,但我认为这应该是足以让你开始。Your 2 main problems are:
First, your loop does not contain any actual operations except a noop
is equal to
And your second logical error is that you initialize the value of
correctChoice
withtrue
, so that your loop condition is never fullfilled and the loop never entered.You should initialize that value as false, and then inside the loop change it to true once the correct choice has been made to exit the loop.
A corrected version of your code would look something like this:
There are more things that could be improved, like catching a
InputMismatchException
to handle your user not entering a number but normal text, but I think this should be enough to get you started.