[英]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();
}
該方法應該將用戶輸入限制為用戶定義的整數范圍,但是即使輸入有效數字,它也仍會在do{...}while(...)
循環內進行循環。 它被提供一個靜態類set
,該類set
由構造函數初始化。 以下是相關的代碼片段:
set
構造函數:
set(int val, int uLim, int lLim) {
this.val = val;
this.uLim = uLim;
this.lLim = lLim;
}
初始化set
:
set max = new set(0, 1, 99);
然后我繼續進行prompt(max)
,但是即使我輸入有效的整數(如60、55或10 prompt(max)
,它也會一直告訴我“請輸入...指定范圍”。循環是否有問題或我在做什么?在其他地方錯了嗎?
似乎無法弄清楚這一點,嘗試使用正則表達式,try-catch塊和parseInt作為替代方案,最終出現不同的錯誤,所以我回到了最簡單的調節用戶輸入的方法...
循環條件為while (x.getVal() <= x.getlLim() || x.getVal() > x.getuLim());
然后將uLim = 1, lLim = 99
設置uLim = 1, lLim = 99
,
顯然,您的“有效”數字1<= 60, 55, 10 <=99
,這就是循環永遠不會結束的原因。
根據您的描述,我認為循環條件應該是while (x.getVal() >= x.getlLim() || x.getVal() < x.getuLim());
您的uLim(upperLimit)低於lLim(lowerLimit):
set(int val, int uLim, int lLim) {
this.val = val;
this.uLim = uLim;
this.lLim = lLim;
}
初始化集:
set max = new set(0, 1, 99);
我會根據電話號碼的大小來訂購電話,而不是在聲明中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.