开发一个类似于创建收据的程序。它需要扫描仪输入:名称和价格。试图使用一个尝试捕获的情况下,一个双不会被输入到价格扫描器。设法使它工作,但只有当异常被抛出一次;如果我在catch块内再次提供不正确的输入,它将失败。我能做些什么让程序处理捕获内的异常?我也只是一个孩子,用我能得到的任何免费资源学习,所以这里的错误可能只是基本的问题/糟糕的编码实践,并且希望这些问题也能被指出。
谢谢!
以下是代码:
Scanner scanPrice = new Scanner(System.in);
System.out.println("Enter the cost: ");
try {
priceTag = scanPrice.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Only numbers. Enter the cost again.");
scanPriceException = new Scanner(System.in);
priceTag = scanPriceException.nextDouble();
}
costs[i] = priceTag;发布于 2014-05-12 00:30:20
这是因为您的try和catch块只运行一次。如果你需要重试直到成功,你需要把它放在一个循环中。只需更改代码块:
Scanner scanPrice = new Scanner(System.in);
System.out.println("Enter the cost: ");
try {
priceTag = scanPrice.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Only numbers. Enter the cost again.");
scanPriceException = new Scanner(System.in);
priceTag = scanPriceException.nextDouble();
} 至:
Scanner scanPrice = new Scanner(System.in);
while (true) {
System.out.println("Enter the cost: ");
try {
priceTag = scanPrice.nextDouble();
break;
} catch (InputMismatchException e) {
System.out.println("Only numbers. Enter the cost again.");
scanPrice.next();
}
}如果在try上存在InputMismatchException,则InputMismatchException块不会到达nextDouble语句。
编辑:忘记添加,但您也需要放弃旧的输入,这样它就不会再次引发异常。因此,scanPrice.next()在最后。有关更多详细信息,请参见此答案:How to handle infinite loop caused by invalid input using Scanner
发布于 2014-05-12 01:15:17
在这里,while(true)意味着直到您的扫描器没有得到所需的输入(在本例中是一个双值),它将一直问您“只输入数字。再次输入成本.”。当扫描器获得正确的输入时,在这种情况下不会抛出"InputMismatchException“,并且执行try块中的block语句,这会将程序控件从而循环中移出。
https://stackoverflow.com/questions/23599372
复制相似问题