java输入任意范围内的数字,仅使用计数器对数字范围和数字值进行JAVA输入验证...

I am trying to complete a task and I am unsure what route to take. I have tried while, if, and a combination of statements and cannot get the input validation I need.

I am trying to validate user input and ensure their input is a number between 0 and 10 (excluding 0 and 10).

Also I need to make sure that what they do enter is a number and not some symbol or letter.

Finally I need a counter that will allow them 3 chances to input the correct information.

The code below is my method I am trying to setup to accomplish this.

private static int getNumericInput(String quantity) {

int count = 0;

String input;

input = JOptionPane.showInputDialog(quantity);

int range = Integer.parseInt(input);

while ((range > 9 || range < 1) && (count < 2)) {

JOptionPane.showMessageDialog(null,

"Sorry that input is not valid, please choose a quantity from 1-9");

input = JOptionPane.showInputDialog(quantity);

count++;

}

if (count == 2) {

JOptionPane.showMessageDialog(null,

"Sorry you failed to input a valid response, terminating.");

System.exit(0);

}

return range;

}

解决方案

As others have said to see if a String is a valid integer you catch a NumberFormatException.

try {

int number = Integer.parseInt(input);

// no exception thrown, that means its a valid Integer

} catch(NumberFormatException e) {

// invalid Integer

}

However I would also like to point out a code change, this is a prefect example of a do while loop. Do while loops are great when you want to use a loop but run the condition at the end of the first iteration.

In your case you always want to take the user input. By evaluating the while loops condition after the first loop you can reduce some of that duplicate code you have to do prior to the loop. Consider the following code change.

int count = 0;

String input;

int range;

do {

input = JOptionPane.showInputDialog(quantity);

try {

range = Integer.parseInt(input);

} catch(NumberFormatException e) {

JOptionPane.showMessageDialog(null, "Sorry that input is not valid, please choose a quantity from 1-9");

count++;

// set the range outside the range so we go through the loop again.

range = -1;

}

} while((range > 9 || range < 1) && (count < 2));

if (count == 2) {

JOptionPane.showMessageDialog(null,

"Sorry you failed to input a valid response, terminating.");

System.exit(0);

}

return range;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值