简体   繁体   中英

What causes the "Exception in thread "main" java.util.InputMismatchException" error?

To begin my question, here is my question prompt:

Create a program using classes that does the following in the zyLabs developer below. For this lab, you will be working with two different class files. To switch files, look for where it says "Current File" at the top of the developer window. Click the current file name, then select the file you need.

(1) Create two files to submit:

ItemToPurchase.java - Class definition
ShoppingCartPrinter.java - Contains main() method
Build the ItemToPurchase class with the following specifications:

Private fields
String itemName - Initialized in default constructor to "none"
int itemPrice - Initialized in default constructor to 0
int itemQuantity - Initialized in default constructor to 0
Default constructor
Public member methods (mutators & accessors)
setName() & getName() (2 pts)
setPrice() & getPrice() (2 pts)
setQuantity() & getQuantity() (2 pts)
(2) In main(), prompt the user for two items and create two objects of the ItemToPurchase class. Before prompting for the second item, call scnr.nextLine(); to allow the user to input a new string. (2 pts)

Ex:

Item 1
Enter the item name: Chocolate Chips
Enter the item price: 3
Enter the item quantity: 1

Item 2
Enter the item name: Bottled Water
Enter the item price: 1
Enter the item quantity: 10

(3) Add the costs of the two items together and output the total cost. (2 pts)

Ex:

TOTAL COST
Chocolate Chips 1 @ $3 = $3
Bottled Water 10 @ $1 = $10

Total: $13  

My code:

ItemToPurhase.java

    public class ItemToPurchase {
   //Private fields - itemName, itemPrice, and itemQuanity
   private String itemName = "none";
   private int itemPrice = 0;
   private int itemQuantity = 0;

   /*Default Constructor
    itemName - Initialized to "none"
    itemPrice - Initialized to 0
    itemQuantity - Initialized ito 0
   */
   
   public ItemToPurchase () {
      this.itemName = "none";
      this.itemPrice = 0;
      this.itemQuantity = 0;
   }   
    
   //public member methods (mutators & accessors)
   
   //setName() & getName() 
   public void setName (String itemName) {
      this.itemName = itemName;
   }
   
   public String getName() {
      return itemName;
   }
   
   //setPrice() & getPrice() 
   public void setPrice (int itemPrice) {
      this.itemPrice = itemPrice;
   }
   
   public int getPrice(){
      return itemPrice;
   }
   
   //setQuantity() & getQuantity() 
   public void setQuantity (int itemQuantity) {
      this.itemQuantity = itemQuantity;
   }
   
   public int getQuantity() {
      return itemQuantity;
   }
   
   //print item to purchase
   
   public void printItemPurchase() {
      System.out.println(itemQuantity + " " + itemName + " $" + itemPrice +  
                         " = $" + (itemPrice * itemQuantity));
   }
}

ShoppingCartPrinter.java

import java.util.Scanner;

public class ShoppingCartPrinter {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      int i = 0;
      String productName;
      int productPrice = 0;
      int productQuantity = 0;
      int cartTotal = 0;
  
      ItemToPurchase item1 = new ItemToPurchase();
      ItemToPurchase item2 = new ItemToPurchase();

      // Get item 1 details from user, create itemToPurchase object
      System.out.println("Item 1");
      
      System.out.println("Enter the item name: ");
      productName = scnr.next();
      item1.setName(productName);
      
      System.out.println("Enter the item price: ");
      productPrice = scnr.nextInt();
      item1.setPrice(productPrice);
      
      System.out.println("Enter the item quantity: ");
      productQuantity = scnr.nextInt();
      item1.setQuantity(productQuantity);
      
      System.out.println("");
 
      // Get item 2 details from user, create itemToPurchase object
      System.out.println("Item 2");
      
      System.out.println("Enter the item name: ");
      productName = scnr.next();
      item2.setName(productName);
      
      System.out.println("Enter the item price: ");
      productPrice = scnr.nextInt();
      item2.setPrice(productPrice);
      
      System.out.println("Enter the item quantity: ");
      productQuantity = scnr.nextInt();
      item2.setQuantity(productQuantity);
      
      System.out.println("");
      
      
      // Add costs of two items and print total
      cartTotal = (item1.getQuantity() * item1.getPrice()) + (item2.getQuantity() * item2.getPrice());
      System.out.println("TOTAL COST");
      // cartTotal = item one price + item two price
      // Totoal Cost
      // item one information
      int item1Total = item1.getPrice() * item1.getQuantity();
      System.out.println(item1.getName() + " " + item1.getQuantity() +  " @ $" + item1.getPrice() + " = $" + item1Total);
      // item two information
      int item2Total = item2.getPrice() * item2.getQuantity();
      System.out.println(item2.getName() + " " + item2.getQuantity() +  " @ $" + item2.getPrice() + " = $" + item2Total);
      // Total output
      System.out.println("");
      System.out.print("Total: $" + cartTotal);
      return;
   }
   
}

Although I am getting no errors for most of the submissions, there are 2 submissions that raise the "Exception in thread "main" java.util.InputMismatchException" error.

Example:

Exited with return code 1.  
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:23)



Output differs. See highlights below. 

Input:

Chocolate Chips
3
1
Bottled Water
1
10

Your output:

Item 1
Enter the item name: 
Enter the item price: 

Expected output(!):

Item 1
Enter the item name: 
Enter the item price: 
Enter the item quantity: 

Item 2
Enter the item name: 
Enter the item price: 
Enter the item quantity: 

TOTAL COST
Chocolate Chips 1 @ $3 = $3
Bottled Water 10 @ $1 = $10

Total: $13

My code seems correct for other inputs that are very similar but for some reason, the compiler that my professor uses keeps prompting this error for a very few cases.

If you have not already done so, I suggest that you read the documentation for class java.util.Scanner .

This line of your code is throwing the InputMismatchException .

productPrice = scnr.nextInt();

That means that scnr read a token that was not an int . This is because your product contained two words, namely Chocolate Chips . So this line of your code only read Chocolate

productName = scnr.next();

and hence method nextInt read Chips which is not an int .

You need to change the code and call method nextLine rather than method next . Again, refer to the documentation to understand why.

Also, after calling method nextInt and before calling method nextLine , you need an extra call to method nextLine . Refer to Scanner is skipping nextLine() after using next() or nextFoo()? to understand why.

Only class ShoppingCartPrinter needs to be changed. Here is the changed code. I have added comments to indicate the changes, namely CHANGE HERE and ADDED THIS LINE .

import java.util.Scanner;

public class ShoppingCartPrinter {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        int i = 0;
        String productName;
        int productPrice = 0;
        int productQuantity = 0;
        int cartTotal = 0;

        ItemToPurchase item1 = new ItemToPurchase();
        ItemToPurchase item2 = new ItemToPurchase();
        // Get item 1 details from user, create itemToPurchase object
        System.out.println("Item 1");

        System.out.println("Enter the item name: ");
        productName = scnr.nextLine(); // CHANGE HERE
        item1.setName(productName);

        System.out.println("Enter the item price: ");
        productPrice = scnr.nextInt();
        item1.setPrice(productPrice);

        System.out.println("Enter the item quantity: ");
        productQuantity = scnr.nextInt();
        item1.setQuantity(productQuantity);

        scnr.nextLine(); // ADDED THIS LINE
        System.out.println("");

        // Get item 2 details from user, create itemToPurchase object
        System.out.println("Item 2");

        System.out.println("Enter the item name: ");
        productName = scnr.nextLine(); // CHANGE HERE
        item2.setName(productName);

        System.out.println("Enter the item price: ");
        productPrice = scnr.nextInt();
        item2.setPrice(productPrice);

        System.out.println("Enter the item quantity: ");
        productQuantity = scnr.nextInt();
        item2.setQuantity(productQuantity);

        System.out.println("");

        // Add costs of two items and print total
        cartTotal = (item1.getQuantity() * item1.getPrice())
                + (item2.getQuantity() * item2.getPrice());
        System.out.println("TOTAL COST");
        // cartTotal = item one price + item two price
        // Totoal Cost
        // item one information
        int item1Total = item1.getPrice() * item1.getQuantity();
        System.out.println(item1.getName() + " " + item1.getQuantity() + " @ $" + item1.getPrice()
                + " = $" + item1Total);
        // item two information
        int item2Total = item2.getPrice() * item2.getQuantity();
        System.out.println(item2.getName() + " " + item2.getQuantity() + " @ $" + item2.getPrice()
                + " = $" + item2Total);
        // Total output
        System.out.println("");
        System.out.print("Total: $" + cartTotal);
        return;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM