我在验证String输入时遇到问题。我想这样做,以便用户不能输入无效的字符串(仅“CIS 280”,“ACC 201”,“CIS 120”,“CIS 185”)。但是,我无法弄清楚如何用字符串来做。
我的问题是
当我在第一个输入对话框中输入无效输入时,程序会进入无限循环,即使我输入有效的字符串:
invalid = JOptionPane.showInputDialog("Please enter a valid class.");
public class arraytest {
public static void main(String[] args) {
int i = 0;
String classInput;
boolean valid = false;
String invalid;
String[][] classNames = {
{"CIS 280", "ACC 201", "CIS 120", "CIS 185"},
{"Tue 5:00", "Mon & Weds 12:20", "Mon & Weds 10:10", "Mon & Weds 12:00" }
};
classInput = JOptionPane.showInputDialog("Please input a class name: ");
do {
for (i = 0; i < classNames[0].length; ++i) {
if(classNames[0][i].equals(classInput)) {
valid = true;
}
}
if(valid == false) {
invalid = JOptionPane.showInputDialog("Please enter a valid class.");
classInput.equals(invalid);
}
} while(valid == false);
JOptionPane.showMessageDialog(null, "The time of that class is: " + classNames[1][i]);
}
}
答案 0 :(得分:0)
而不是
get users input
do{
validate input
if input is wrong ask again //btw here is your error,
//check where you are storing user's input
}while(input is wrong)
尝试
do{
get users input
validate input
}while(input is wrong)
另一件事是你正在迭代直到行的末尾,这将使i
等于行的length
。您需要在找到正确值时停止迭代,以便在
i
JOptionPane.showMessageDialog(null, "The time of that class is: " + classNames[1][i]);