-1

I understand using nextInt() first solve the problem but the assignment required me to do it that way. Also using next() is not an acceptable solution.

I have a for loop to create 3 objects and set their property name and price the first execution work fine but the second and third save an empty string to my itemsList[i].setName(keyBoard.nextLine()).

how to solve this issue?

 for (int i = 0; i < itemsList.length; i++) { // for loop iterate 3 times
        itemsList[i] = new Item(); // Create new object every time the loop iterate
        System.out.println("Enter an item's name");
        itemsList[i].setName(keyBoard.nextLine());
        keyBoard.nextLine(); // To avoid the skip line that is done by the nextLine() method
        System.out.println("Enter an item's price");
        itemsList[i].setPrice(keyBoard.nextDouble());
    }

//method to display the result

 public static void displayItemsName(Item[] items){
    for (int i = 0; i < items.length; i++) {
        System.out.println(items[i].getName());
    }
}

execution result

Enter an item's name

hhhh

Enter an item's price

45

Enter an item's name

gggg

Enter an item's price

45

Enter an item's name

peas

Enter an item's price

33

hhhh

the above two lines are empty

Abdulrazzaq
  • 61
  • 1
  • 6

1 Answers1

1

You need to call .nextLine() after .nextDouble() to consume the newline character.

itemsList[i].setPrice(keyBoard.nextDouble());
keyBoard.nextLine(); // add this in your for loop

sleepToken
  • 1,804
  • 1
  • 12
  • 21