For the cycle, the first command is not executed after the second time

Here is my code:

import java.util.Scanner; public class BankAccount1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); char pickup; char size; char type; String name; double cost=0.0; int i; for (i=0; i<2; i++) { System.out.println("What is your name?"); name = input.nextLine(); System.out.println("size of pizza: "); size = input.next().charAt(0); System.out.println("type of pizza: "); type = input.next().charAt(0); System.out.println("pick up or delivery?"); pickup = input.next().charAt(0); if(size == 'S' || type == 'V') {cost = 10.0;} else if(size == 'M' || type == 'V') {cost = 12.25;} else if(size == 'L' || type == 'V') {cost = 14.50;} else if(size == 'S' || type == 'C') {cost = 7.0;} else if(size == 'M' || type == 'C') {cost = 8.0;} else if(size == 'L' || type == 'C') {cost = 9.0;} if(pickup == 'D'){ cost=cost+1.50; System.out.println("Name: "+name+". Your cost is: "+cost);} else { System.out.println("Name: "+name+". Your cost is: "+cost);} } } } 

I have a for loop in my code and it asks for name, size, type and pickup. At the first start, it asks you to enter all the fields, but the second time the name field does not allow me to enter the name for any reason, it prints "What is your name?". but it doesn’t allow me to enter a name ...? Can someone tell me why? Thanks.

this is how it looks: http://i.stack.imgur.com/eb1BA.jpg

+4
source share
3 answers

Due to

 input.next() 

does not use newline characters, they are passed back to your loop and do not allow you to enter a value. You will need to add:

 for (i = 0; i < 2; i++) { // existing input.next() statements in here ... input.nextLine(); } 

at the end of the for loop to fix it.

+3
source

When you use Scanner with System.in , the data is not read from System.in until a new line (you hit Enter ). So, what do you actually have in the scanner buffer:

 Jake\nL\nV\nD\n 

The key here is that D not sent to the scanner buffer until you press enter. That's why there \n at the end. Usually, when you call input.next() , the previous stray new line becomes consumed. But when you call input.nextLine() second / third time around the for loop, it reads this jagged ending newline:

  here ----v Jake\nL\nV\nD\n 

So, you get an empty line, essentially reading everything between D and \n that nothing.

You need to call nextLine() every time and call charAt(0) on the resulting line.

+3
source

Replace input.next () with input.nextLine (). That should fix it.

+2
source

Source: https://habr.com/ru/post/1440174/


All Articles