java showinputdialog,JOptionPane.showInputDialog的用户输入验证

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;

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?

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.

Thanks in advance!

解决方案

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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值