javainputmismatchexception

InputMismatchException need more inputs?


I am receiving a InputMismatchException

java ShoppingTime 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 ShoppingTime.main(ShoppingTime.java:88)

From my understanding it is because I am not providing enough inputs in my main function? But I am lost on what I need to add. would it be another price input? I don't think so bc I am only taking a string input and integer input.

public class ShoppingTime{
public static void main(String args[]) throws FileNotFoundException {
    File read = new File("Products.txt");
    Scanner sc = new Scanner(read);
    ArrayList<Product> ar = new ArrayList<Product>();
    while (sc.hasNextLine()) {
        String product = sc.nextLine();
        int price = sc.nextInt();
        ar.add(new Product(product, price));
    }
    int ch;
    Cart c = new Cart();
    sc = new Scanner(System.in);
    do {
        System.out.println("Menu");
        System.out.println("1 Add item");
        System.out.println("2 View Cart");
        System.out.println("3 Clear Cart");
        System.out.println("4 Checkout");
        System.out.println("5 Exit");
        ch = sc.nextInt();
        if (ch == 1) {
            c.addItem(ar);
        }
        if (ch == 2) {
            c.viewCart();
        }
        if (ch == 3) {
            c.clearCart();
        }
        if (ch == 4) {
            c.checkOut();
        }

    } while (ch != 5);

}

}


Solution

  • all the line is a string, so you have read the whole line including the wrapped int in the first nextLine() call.you should just read with nextLine() and parse the int out of it.