java try catch 失败重试_java - 在java中的try-catch中重试try块 - SO中文参考 - www.soinside.com...

在java中的try-catch中重试try块

问题描述 投票:0回答:3

我是java的新手,有以下问题。我已经找到了几个答案,但仍然不清楚如何实现while块来解决问题:

在下面的代码中,我试图从用户输入接收有关“产品名称”和“价格”的信息。 product name是使用scanner.next()函数检索的字符串,价格是double。如果用户提供的产品名称与使用空格不一致,则我会在catch块中捕获一个错误。问题是我如何回到try块并给用户第二次机会输入产品名称值而不是退出系统?我对这个问题进行了很多搜索,但仍未找到解决方案。

String[] sArrProdName = new String[newUser.getNumberOfItemsInStock()] ;

double[] sArrPrice = new double[newUser.getNumberOfItemsInStock()];

for(int i=0;i

{

try {

System.out.println("Enter product Name: ");

sArrProdName[i]= s.next();

System.out.println("Price? : ");

sArrPrice[i] = s.nextDouble();

}

catch (InputMismatchException e) {

prompt("Enter product name correctly");

}

}

java

3个回答

0

投票

像这样的东西可以工作:

class ProductInfo{

public static final int NUM_RETRY = 3;

public static void main(String[] args) {

String[] sArrProdName = new String[newUser.getNumberOfItemsInStock()] ;

double[] sArrPrice = new double[newUser.getNumberOfItemsInStock()];

int cont;

for(int i=0;i

cont = 0;

while (cont<=NUM_RETRY){

try {

System.out.println("Enter product Name: ");

sArrProdName[i]= s.next();

System.out.println("Price? : ");

sArrPrice[i] = s.nextDouble();

}catch (InputMismatchException e) {

cont++;

prompt("Enter product name correctly");

}

}

}

}

}

0

投票

我刚刚写了这个,但设置看起来像这样:

String[] sArrProdName = new String[newUser.getNumberOfItemsInStock()] ;

double[] sArrPrice = new double[newUser.getNumberOfItemsInStock()];

for(int i=0;i

{

boolean retryInput = true;

while (retryInput)

{

try {

System.out.println("Enter product Name: ");

sArrProdName[i]= s.next();

System.out.println("Price? : ");

sArrPrice[i] = s.nextDouble();

retryInput = false;

}

catch (InputMismatchException e) {

prompt("Enter product name correctly");

}

}

}

这里的基本前提是try块可以被认为是它自己独立的if语句 - if正在尝试的任务完成,执行块的其余部分。因此,可以将简单的布尔标志设置为仅在验证代码后更改。

当然,在retryInput = false;本身之前还有你想做的检查;这只是为了演示更改布尔标志的位置。

编辑:向Dici大喊,他们的评论是正确的。

0

投票

例:

RetryCatch retryCatchSyncRunnable = new RetryCatch();

retryCatchSyncRunnable

// For infinite retry times, just remove this row

.retryCount(3)

// For retrying on all exceptions, just remove this row

.retryOn(ArithmeticException.class, IndexOutOfBoundsException.class)

.onSuccess(() -> System.out.println("Success, There is no result because this is a runnable."))

.onRetry((retryCount, e) -> System.out.println("Retry count: " + retryCount + ", Exception message: " + e.getMessage()))

.onFailure(e -> System.out.println("Failure: Exception message: " + e.getMessage()))

.run(new ExampleRunnable());

您可以编写自己的匿名函数,而不是Example Runnable

热门问题

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值