0

With this code, I'm looking to get 2 foods from the user. The print statement with food1 prints and displays the string the user entered correctly in the console. With the print statement for food2, it will print the statement but the string that the user input will not display along with it. I've tried using print/println neither change anything.

for(x=1; x <= 2; x++)

System.out.print("Enter nationality of the food: ");
Nation = sc.nextLine();
System.out.print("Enter your first food: ");

food1 = sc.nextLine();
System.out.print("Enter food price: ");
value1 = sc.nextDouble();

System.out.print("Enter your second food choice: ");
food2 = sc.nextLine();
sc.next();
System.out.print("Enter food price: ");
value2 = sc.nextDouble();
total = (value1 + value2);
System.out.println("Your food nationality: " + Nation);
System.out.printf("Your total price is: %.2f\n", total);
System.out.print("Would you like to list your items? (1 For Yes/2 For No)");
choice = sc.nextInt();
while( choice == 1)

  System.out.println("Your first food: " + food1); // This one displays correctly in the console 
  System.out.println("Your second food: " + food2); // This one does not display the string that the user inputted in the console 
  choice++;
  sc.nextLine();

1 Answers1

0

sc.nextDouble() does not take in the entire line, only the next decimal value. Therefore you will need to read in that line before reading in food2.

System.out.print("Enter your first food: ");
food1 = sc.nextLine();
System.out.print("Enter food price: ");
value1 = sc.nextDouble();
sc.nextLine(); // add this line

System.out.print("Enter your second food choice: ");
food2 = sc.nextLine();
sc.next(); // I am not sure what you are doing here. If I understand your code correctly, you can delete this
System.out.print("Enter food price: ");
value2 = sc.nextDouble();
sc.nextLine(); // add this line
Jimmy Xin
  • 76
  • 4