0

i am trying to enter a book title "hoopa doopa"into my object array. when i try it throws a java.util.InputMismatchException.If i enter a string that has no spaces like"hoopa" the code will run fine all of the way through. What is causing this and how can I fix it? please help thanks

    import java.io.*;
    import java.util.Scanner;
    public class Test {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner  input = new Scanner(System.in);
    int counter = 0;
    int numberOfProducts=0; //variable for when the user is asked to enter    input the number of products to be entered

    do {                                                               //this will validate the user input
        System.out.println("How many products would you like to enter");
        while (!input.hasNextInt()) {
            System.out.println("That's not a number!");
            input.next(); // this is important!
        }
        numberOfProducts = input.nextInt();
    } while (numberOfProducts <= 0);

                                        //end of   the do while loop




    Products[] products;
    products = new Products[numberOfProducts+4];//create a array the size of   the user input that was gathered
    for (int i=0;i<numberOfProducts;i++)
    {
        products[i+4]= new Products();  // create each actual Person
        System.out.println("What is the product #: ");
        products[i+4].setItemNumber(input.nextInt());
        System.out.println("What is the book name: ");
        products[i+4].setNameOfProduct(input.next());
        System.out.println("How many are in stock: ");
        products[i+4].setUnitsInStock(input.nextInt());
        System.out.println("What is the cost of the Item: ");
        products[i+4].setPrice(input.nextDouble());
        counter++;




    }




     products[0] = new Products(0001,"The Red Rose",1,29.99);
     products[1] = new Products(0002,"The Bible",3,11.99);
     products[2] = new Products(0003,"End of the Programm",2,29.99);
     products[3] = new Products(0004,"WHAT!!! the....",1,129.99);
    //____________________________________________________________4 products that are already made

     for (int i=0;i<numberOfProducts+4;i++) 
     {
         System.out.println(products[i].toString());
         input.nextLine();

     }


    }

    }

this is the other class import java.text.NumberFormat;

    public class Products 
    {
private int itemNumber;
private String nameOfProduct;
private int unitsInStock;
private double unitPrice;

public Products()
{
itemNumber = 0;
nameOfProduct = null;
unitsInStock = 0;
unitPrice = 0.0;
}

public Products(int num,String name,int inStock,double price)
{
    itemNumber = num;
    nameOfProduct = name;
    unitsInStock = inStock;
    unitPrice = price;
}

public int getItemNumber() 
{
    return itemNumber;
}

public void setItemNumber(int newValue) 
{
    itemNumber=newValue;
}
    //----------------------------------------------
    public String getNameOfProduct() 
{
    return nameOfProduct;
}

public void setNameOfProduct(String newValue) 
{
    nameOfProduct=newValue;
}
    //----------------------------------------------
    public int getUnitsInStock()
{
    return unitsInStock;
}
public void setUnitsInStock(int newValue)
{
    unitsInStock = newValue;
}
    //-----------------------------------------------
    public double getPrice()
{
    return unitPrice;
}
public void setPrice(double newValue)
{
    unitPrice = newValue;
}
    //_______________________________________________   


 public double calculateTotalItemValue() //method that uses quantity on hand and   price part3 1.A
 {
        return getUnitsInStock()* getPrice();

 }//end of method



 @Override
    public String toString() 
 {
        NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
        return"\nItem Number: "+getItemNumber() +
        "\nItem Name: "+getNameOfProduct()+
         "\nItem Quantity: " +getUnitsInStock()+
        "\nItemPrice:" +currencyFormat.format(getPrice())
        +"\nValue of Inventory: "    +currencyFormat.format(this.calculateTotalItemValue());//part3 1.B


   }

    }
3
  • Scanner#nextInt throws InputMismatchException - if the next token does not match the Integer regular expression, or is out of range. "hoopa" is not an integer. Commented Nov 27, 2013 at 5:23
  • use input.nextLine() instead for receiving string value with spaces Commented Nov 27, 2013 at 5:25
  • I just tried the input.nextLine() and oddly enough it caused the program to skip the input and go to the next system.out.println Commented Nov 27, 2013 at 5:30

4 Answers 4

1

The Scanner sees the space in the book name as a delimiter since you are using the next() method. So when you go to read the nextInt() for the stock amount, the Scanner index is after the space in the book name String, and pulls in the remaining String data, which doesn't convert to an int. Instead, try something like this:

System.out.println("What is the book name: ");
input.nextLine();
products[i+4].setNameOfProduct(input.nextLine());

If you do not add the input.nextLine();, then it will appear as though the book name prompt gets skipped.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for your help. i feel silly for spending so many hours overlooking such a small bug. It is so nice to have a fresh pair of eyes look at the code. thanks md_rasler
0

Scanner input = new Scanner(System.in);

Actually you are using scanner to get input and by default scanner delimiter is space. So you have to change the default delimiter of your code.

2 Comments

You can use nextLine() method also.
Thanks for your help i totally miss read you post about the nextLine() and wrote it the wrong way. It is working fine now. thank you so much for your help!
0

I think this is your problem:

products[i+4].setNameOfProduct(input.next());

What input.next() does is it reads the input from the user, until it reaches white space (the space between hoopa doopa). The function then passes hoopa to the setNameOfProduct method, and then passes doopa to the nextInt function, which gives a runtime error.

To fix your problem I would code

products[i+4].setNameOfProduct(input.nextLine());

Edit: nextLine() function passes all characters up to the carriage return

2 Comments

i have tried the input.nextLine() and when i run the program it skips it and doesnt allow the user to enter a name at all.
I have looked at the code for hours and can't understand why this is being skipped
0

Problem :

products[i+4].setNameOfProduct(input.next());

Solution 1 : Just create another Scanner object for reading input with spaces

 Scanner sc1=new Scanner(System.in);
 products[i+4].setNameOfProduct(sc1.nextLine());

Solution 2 : Or to use same scanner object

 input.nextLine(); //Include this line before getting input string
 products[i+4].setNameOfProduct(input.nextLine());

1 Comment

If I use next line it skips over it and does not allow me to enter anything

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.