在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
热门问题