首先感谢你们,你们在堆栈溢出时所做的一切。它帮助了我很多次! 今天我的问题是使用与扫描仪一起使用的try / catch指令有点问题。看看我将产品添加到配方的方法:
public static void addProducts(List<Product> product, Scanner sc)
{
if (run == true)
{
Maths calc = new Maths();
//Some instructions in Polish, not needed here :)
while (true)
{
String name = null;
double quantity = 0;
double pricePerUnit = 0;
try
{
name = sc.nextLine();
if (name.equals("0") || name.equals("exit"))
{
Logic.run = false;
break;
}
quantity = sc.nextDouble();
sc.nextLine();
pricePerUnit = sc.nextDouble();
sc.nextLine();
product.add(new Product(product.size() + 1, name, calc.round(quantity, 2), calc.round(pricePerUnit, 2)));
System.out.println("Product added: " + "\n" + product.get(product.size() - 1));
} catch (InputMismatchException e)
{
System.out.println("Error! Please repeat your last input.");
}
}
double num = 0;
for (Product p : product)
{
num += p.getPrice();
}
Maths.setTotalPrice(num);
System.out.println("Total: " + num);
} else
{
System.out.println("You have already added products to the recipe!");
}
}
正如你可以看到我在try / catch指令中读取String,double和double。例如,当在配方中添加“土豆”时,我不小心写了“马”,其中数量应该是我得到一个名为“马”而不是“马铃薯”的产品。明白了吗?我这里有一只黄色的鸭子,但用我的母语比用英语更容易解释:) 如果有什么不清楚我会尽力解释,谢谢!
答案 0 :(得分:1)
当你这样做时:
quantity = sc.nextDouble();
sc.nextLine();
你丢掉任何额外的输入,没有确认。如果要限制用户仅在一行中输入数字而不输入任何其他内容,请使用:
quantity = Double.parseDouble(sc.nextLine()); // maybe add .trim()
如果您保持代码不变,请记住,当InputMismatchException
被抛出时,Scanner
仍然位于错误输入的开头(开头),因此您需要丢弃该代码:
} catch (InputMismatchException e)
{
System.out.println("Error! Please repeat your last input.");
sc.nextLine(); // discard bad input
}
当然,您的代码将循环并提示所有3个输入,因此错误消息有点误导。