问题描述
我正在学习JAVA,并且在代码的这一特定部分遇到了一些麻烦.我搜索了多个站点,并尝试了许多不同的方法,但似乎无法弄清楚如何实现一种适用于不同可能性的方法.
I'm just learning JAVA and having a bit of trouble with this particular part of my code. I searched several sites and have tried many different methods but can't seem to figure out how to implement one that works for the different possibilities.
int playerChoice = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number for corresponding selection:\n"
+ " (1) - ROCK\n (2) - PAPER\n (3) - SCISSORS\n")) - 1;
我想我即使在用户没有输入以及输入不是1、2或3的情况下,也需要进行某种类型的验证.有人对我如何完成此操作有建议吗?
I imagine I need to have some type of validation even for when the user has no input as well as an input that is not 1, 2 or 3. Anyone have suggestions on how I can accomplish this?
我尝试了while循环,一个if语句,用于在将输入转换为整数之前检查null,以及几种其他类型的if else if方法.
I tried a while loop, an if statement to check for null before converting the input to an integer, as well as a few different types of if else if methods.
提前谢谢!
推荐答案
您需要执行以下操作来处理错误的输入:
You need to do something like this to handle bad input:
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
}
这篇关于JOptionPane.showInputDialog的用户输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!