java两边条件同时满足_java-继续提示直到满足条件

我正在练习异常处理,并或多或少地掌握了基本概念.

我一直在寻找如何通过提示用户输入满足特定条件的值来继续执行的方法,尽管通过使用循环捕获了异常

我有这个特定的代码,要求用户输入一个范围之间的值,并具有异常处理以捕获是否正在输入字符串.但是,该程序在打印出异常处理后停止执行.

有什么想法可以实现异常处理后可以继续执行程序的循环或任何其他方法?

Scanner scanner = new Scanner(System.in);

int num = 0;

try

{

System.out.print("Please enter a number between 1 to 50 : ");

num = scanner.nextInt();

}

catch (InputMismatchException e) {

System.out.println("Not a number");

return;

}

while (num > 50 || num < 1) {

System.out.print("Out of range. Enter a number between 1 to 50 : ");

num = scanner.nextInt();

}

System.out.println("The number is : " + num);

解决方法:

用这个:

Scanner scanner = new Scanner(System.in);

boolean isInputValid = false; // input flag, valid = true / invalid = false

int num = 0;

while(!isInputValid) {

try

{

System.out.print("Please enter a number between 1 to 50 : ");

num = scanner.nextInt();

// Input is a valid integer

if (!(num > 0 && num < 51)) { // input out of range

System.out.print("Out of range.");

}

else

isInputValid = true; // input valid, proceed & break loop

}

catch (InputMismatchException ex) { // input not an integer

System.out.println("Not a number");

scanner.next();

}

catch (Exception ex) {

ex.printStackTrace();

}

}

System.out.println("The number is : " + num);

标签:exception,java

来源: https://codeday.me/bug/20191119/2034869.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值