[英]Java: Infinite looping within while loop when trying to limit user input with do-while
static int prompt(set x) {
Scanner input = new Scanner(System.in);
do {
System.out.println("Please enter an integer within the specified range.");
while (!input.hasNextInt()) {
System.out.println("Please enter a valid integer.");
input.next();
}
System.out.println("input received");
x.setVal(input.nextInt());
} while (x.getVal() <= x.getlLim() || x.getVal() > x.getuLim());
input.close();
return x.getVal();
}
This method is supposed to limit user input to a user-defined range of integers, but it keeps looping within the do{...}while(...)
loop even when I enter valid numbers. 该方法应该将用户输入限制为用户定义的整数范围,但是即使输入有效数字,它也仍会在
do{...}while(...)
循环内进行循环。 It is fed a static class set
, which is initialized with a constructor. 它被提供一个静态类
set
,该类set
由构造函数初始化。 Here are the relevant fragments of code: 以下是相关的代码片段:
set
constructor: set
构造函数:
set(int val, int uLim, int lLim) {
this.val = val;
this.uLim = uLim;
this.lLim = lLim;
}
Initializing set
: 初始化
set
:
set max = new set(0, 1, 99);
I then proceed to prompt(max)
, but it keeps telling me "Please enter...specified range" even though I enter a valid integer like 60, 55, or 10. Are there any problems with the loop or am I doing something wrong somewhere else? 然后我继续进行
prompt(max)
,但是即使我输入有效的整数(如60、55或10 prompt(max)
,它也会一直告诉我“请输入...指定范围”。循环是否有问题或我在做什么?在其他地方错了吗?
Couldn't seem to figure this out, tried using regexs, try-catch blocks and parseInt as alternatives, ended up with different errors so I went back to this simplest method of regulating user input... 似乎无法弄清楚这一点,尝试使用正则表达式,try-catch块和parseInt作为替代方案,最终出现不同的错误,所以我回到了最简单的调节用户输入的方法...
The loop condition is while (x.getVal() <= x.getlLim() || x.getVal() > x.getuLim());
循环条件为
while (x.getVal() <= x.getlLim() || x.getVal() > x.getuLim());
And you set uLim = 1, lLim = 99
, 然后将
uLim = 1, lLim = 99
设置uLim = 1, lLim = 99
,
Obviously, your "valid" number 1<= 60, 55, 10 <=99
, that's why the loop never ends. 显然,您的“有效”数字
1<= 60, 55, 10 <=99
,这就是循环永远不会结束的原因。
According to your description, I think the loop condition should be while (x.getVal() >= x.getlLim() || x.getVal() < x.getuLim());
根据您的描述,我认为循环条件应该是
while (x.getVal() >= x.getlLim() || x.getVal() < x.getuLim());
Your uLim (upperLimit) is below the lLim (lowerLimit): 您的uLim(upperLimit)低于lLim(lowerLimit):
set(int val, int uLim, int lLim) {
this.val = val;
this.uLim = uLim;
this.lLim = lLim;
}
Initializing set: 初始化集:
set max = new set(0, 1, 99);
I would order numbers according to their size, as in your call, not in the declaration. 我会根据电话号码的大小来订购电话,而不是在声明中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.