java scanner输入多个,Java Scanner验证返回第二个输入

I have a function here where it verifies the user input if its a number or within bounds.

public static int getNumberInput(){

Scanner input = new Scanner(System.in);

while(!Inputs.isANumber(input)){

System.out.println("Negative Numbers and Letters are not allowed");

input.reset();

}

return input.nextInt();

}

public static int getNumberInput(int bound){

Scanner input = new Scanner(System.in);

int val = getNumberInput();

if(val > bound){

System.out.println("Maximum Input is only up to: "+ bound+" Please Try Again: ");

input.reset();

getNumberInput(bound);

}

return val;

}

Each time I call getNumberInput(int bound) method with this function

public void askForDifficulty(){

System.out.print("Difficulty For This Question:\n1)Easy\n2)Medium\n3)Hard\nChoice: ");

int choice = Inputs.getNumberInput(diff.length);

System.out.println(choice);

}

if I inserted an out of bound number lets say the only maximum number is 5. the getNumberInput(int bound) will call itself again. and when I insert the correct or within bound value it will only return to me the first value/previous value I inserted

解决方案

The if in the getNumberInput(int bound) should be a while. EDIT You should also combine the two methods:

public static int getNumberInput(int bound){

Scanner input = new Scanner(System.in);

for (;;) {

if (!Inputs.isANumber(input)) {

System.out.println("Negative Numbers and Letters are not allowed");

input.reset();

continue;

}

int val = getNumberInput();

if (val <= bound) {

break;

}

System.out.println("Maximum Input is only up to: "+ bound+" Please Try Again: ");

input.reset();

}

return val;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值