0

I am designing a simple program where a user inputs a string value for item # 1's name and then an integer value for item # 1's price and then an integer value for item # 1's quantity. When I compile the program and then run it it allows me to enter a user input for the item # 1's name but not for item # 2's name. I am not quite sure why this is because it takes user inputs for item price # 2 and item quantity # 2. Why is this happening?

Here are both of the relevant class files:

ItemToPurchase.java:

public class ItemToPurchase {
  private String itemName;
  private int itemPrice;
  private  int itemQuantity;

public void defaultValues() {
  itemName = "none";
  itemPrice = 0;
  itemQuantity = 0;
}

public void setName(String newName) {
  itemName = newName;
}

public String getName() {
  return itemName;
}

public void setPrice(int newPrice) {
  itemPrice = newPrice;
}

public int getPrice() {
  return itemPrice;
}

public void setQuantity(int newQuantity) {
  itemQuantity = newQuantity;
}

public int getQuantity() {
  return itemQuantity;

  }
}

And the class containing the main class-

ShoppingCartPrinter.java:

import java.util.Scanner;

public class ShoppingCartPrinter {
  public static void main(String [] args) {
    Scanner scnr = new Scanner(System.in);
    ItemToPurchase item1 = new ItemToPurchase();
    ItemToPurchase item2 = new ItemToPurchase();

    System.out.println("Item 1");
    System.out.println("Enter the item name:");
    item1.setName(scnr.nextLine());
    System.out.println(item1.getName());

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

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

    System.out.println("");


    System.out.println("Item 2");
    System.out.println("Enter the item name:");
    item2.setName(scnr.nextLine());
    System.out.println(item2.getName());

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

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


    scnr.close();


  }

}
Darien Springer
  • 467
  • 8
  • 17

1 Answers1

2

Thats because the Scanner#nextInt method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine

Workaround: try replacing scnr.nextInt() with Integer.parseInt(scnr.nextLine())

  • I guess my question is why I was not allowed to enter a String for item2. Perhaps I just am having a hard time knowing how Scanner works (which is part of the issue that will require further research), but why would the interactions screen just skip over that? Is it because in nextInt there is implied whitespace after what you input? – Darien Springer Feb 10 '17 at 05:14