Per*_*erd 5 java validation joptionpane
我刚刚学习JAVA并且在代码的这个特定部分遇到了一些麻烦.我搜索了几个网站并尝试了许多不同的方法,但似乎无法弄清楚如何实现一个适用于不同可能性的方法.
int playerChoice = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number for corresponding selection:\n"
+ " (1) - ROCK\n (2) - PAPER\n (3) - SCISSORS\n")) - 1;
Run Code Online (Sandbox Code Playgroud)
我想我需要进行某种类型的验证,即使用户没有输入以及不是1,2或3的输入.任何人都有关于如何实现这一点的建议?
我尝试了一个while循环,一个if语句在将输入转换为整数之前检查null,以及几个不同类型的if else if方法.
提前致谢!
你需要做这样的事情来处理错误的输入:
boolean inputAccepted = false;
while(!inputAccepted) {
try {
int playerChoice = Integer.parseInt(JOption....
// do some other validation checks
if (playerChoice < 1 || playerChoice > 3) {
// tell user still a bad number
} else {
// hooray - a good value
inputAccepted = true;
}
} catch(NumberFormatException e) {
// input is bad. Good idea to popup
// a dialog here (or some other communication)
// saying what you expect the
// user to enter.
}
... do stuff with good input value
Run Code Online (Sandbox Code Playgroud)
}
| 归档时间: |
|
| 查看次数: |
17363 次 |
| 最近记录: |