我的代碼應該要求用戶輸入一個 1 到 10 之間的數字。如果他們輸入一個 1 到 10 之間的數字,那么它會說謝謝并到此結束。如果不是,它應該回圈并說,請輸入一個介于 1 和 10 之間的數字,然后再試一次。然后它將再次使用戶輸入。我的問題是,在第二次輸入后,即使他們第二次輸入錯誤,它也會自動結束回圈。順便說一句,我對編碼很陌生,所以請在評論中對我放輕松 XD。有人請幫忙,謝謝。這是我的代碼:
import javax.swing.*;
public class LoopLecture {
public static void main(String[] args) {
int MIN = 1;
int MAX = 10;
String rating;
rating = JOptionPane.showInputDialog(null, "Please enter your rating of Krabbypatties on a scale of"
MIN "to" MAX ".With" MIN "meaning youhated it and" MAX "meaning you loved it.");
int rating2 = Integer.parseInt(rating);
while (rating2 < MIN || rating2 > MAX) {
JOptionPane.showMessageDialog(null, "You must enter a value between " MIN "and" MAX ".");
JOptionPane.showMessageDialog(null, "Please try again.");
rating = JOptionPane.showInputDialog(null, "Please enter your rating of Krabbypatties on a scale of"
MIN "to" MAX ".With" MIN "meaning youhated it and" MAX "meaning you loved it.");
if (rating2 >= MIN && rating2 <= MAX)
break;
}
JOptionPane.showMessageDialog(null, "Thank you!");
}
}
uj5u.com熱心網友回復:
在 for 回圈中嘗試將新值分配給 rating2
rating = JOptionPane.showInputDialog(null, "請輸入您對 Krabby 的評分
rating2 = JOptionPane.showInputDialog(null, "請輸入您對 Krabby 的評分
uj5u.com熱心網友回復:
while (true) { // creates infinite while loop
break; // ends an infinite loop
}
你的 if 陳述句中有一個break;運算式,所以我相信你明白它是如何作業的,但試著讓回圈無限,如上所示。
uj5u.com熱心網友回復:
更好地解決它:
- 決議
rating為rating2回圈 - 如果數字在 1 到 10 之間,則中斷
- catch
NumberFormatException,不需要做任何事情,忽略它
public static void main(String[] args) {
int MIN = 1;
int MAX = 10;
String rating = JOptionPane.showInputDialog(null, "Please enter your rating of Krabbypatties on a scale of"
MIN "to" MAX ".With" MIN "meaning youhated it and" MAX "meaning you loved it.");
while (true) {
try {
int rating2 = Integer.parseInt(rating);
if (rating2 >= MIN && rating2 <= MAX) {
break;
}
} catch (NumberFormatException ignored) {
}
JOptionPane.showMessageDialog(null, "You must enter a value between " MIN "and" MAX ".");
JOptionPane.showMessageDialog(null, "Please try again.");
rating = JOptionPane.showInputDialog(null, "Please enter your rating of Krabbypatties on a scale of"
MIN "to" MAX ".With" MIN "meaning youhated it and" MAX "meaning you loved it.");
}
JOptionPane.showMessageDialog(null, "Thank you!");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/510414.html
標籤:爪哇循环选项窗格
上一篇:倒計時回圈猜謎游戲的機會
下一篇:如何在java中合并2個陣列?
