Zunächst einmal vielen Dank für alles, was Sie tun, Jungs hier auf Stack Overflow. Es hat mir sehr oft geholfen! Mein Problem heute ist ein kleines Problem mit Versuch/Fang Anweisung mit Scanner. Werfen Sie einen Blick auf meine Methode für das Hinzufügen von Produkten zu einem Rezept:Java Scanner versuchen fangen mehrere Datentypen
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!");
}
}
Wie Sie im Lese String, Doppel- und Doppel im try/catch Anweisung sehen. Wenn ich zum Beispiel "Kartoffeln" zum Rezept hinzufüge, schreibe ich zufällig "Pferd", wo die Menge sein sollte, bekomme ich ein Produkt namens "Pferd" statt "Kartoffeln". Ist das klar? Ich habe hier eine gelbe Ente, aber es ist einfacher, sie in meiner Muttersprache zu erklären als auf Englisch :) Wenn etwas unklar ist, werde ich mein Bestes geben, um zu erklären, danke!
Sie können 'if (run)' anstelle von 'if (run == true) 'verwenden. – dorukayhan
Nur bestätigen: ist Ihre Eingabe 3 Zeilen für jeden Artikel? Name, Menge, Preis? – Bohemian
Erhalten Sie Fehler? Was funktioniert nicht? – sebenalern