I have the following code
public class ShoppingCartPrinter {
public static void main(String[] args) {
String productName;
int productPrice = 0;
int productQuantity = 0;
int cartTotal = 0;
String testStr = "Chocolate Chips\n3\n1\nChocolate Chips\n3\n1";
Scanner scnr = new Scanner(testStr);
productName = scnr.nextLine();
System.out.println("1st Name " + productName);
productPrice = scnr.nextInt();
System.out.println("1st Price " + productPrice);
productQuantity = scnr.nextInt();
System.out.println("1st Quantity " + productQuantity);
System.out.println();
//scnr.nextLine();
productName = scnr.nextLine();
System.out.println("2nd Name " + productName);
productPrice = scnr.nextInt();
System.out.println("2nd Price " + productPrice);
productQuantity = scnr.nextInt();
System.out.println("2nd Quantity " + productQuantity);
}
}
So if I don't include line 27, I got an output with error message:
1st Name Chocolate Chips
1st Price 3
1st Quantity 1
2nd Name
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at ShoppingCartPrinter.main(ShoppingCartPrinter.java:30)
I understand the scnr.nextLine() at line 28 didn't read correctly because the previous scnr.nextInt() didn't consume the /n. But, I don't understand why the scnr.nextInt() at line 31 won't just continue to read the next integer in the string?
Also, if the nextInt() can only read within one line, or it can't pass the /n, then the second nextInt() to read the 1st quantity should also give an error, however it didn't.