首先感谢您在堆栈溢出时所做的一切。它帮了我很多次! 今天我的问题是使用try/catch指令和扫描器一起使用的一个小问题。看看我的方法添加到产品配方:Java扫描器尝试捕获多种数据类型
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语句指令。例如,在食谱中添加“土豆”时,我意外地在数量应该写的“马”上写下名为“马”的产品,而不是“土豆”。明白了吗?我在这里有一只黄色的鸭子,但用我的母语比在英语中更容易解释:) 如果有什么不清楚的地方,我会尽我所能解释,谢谢!
您可以使用'if(run)'而不是'if(run == true)'。 – dorukayhan
只需确认:您的输入是每行3行?名称,数量,价格? – Bohemian
您是否收到错误?什么不起作用? – sebenalern