For loop does not execute the first command after 2nd time
Here is my code:
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 the name, size, type and pickup. The first time it is run, it asks all fields to be entered, but for the 2nd time, the name field does not let me input the name for some reason, it prints the "What is your name?" but it does not let me enter the name...? can someone tell me why?
Thanks.
Click on the picture for more details:
Attachment 1479
Re: For loop does not execute the first command after 2nd time
The Scanner.next method reads and returns the next word only. It does not read an EOL. So the next time around the loop when you call nextLine it does read the EOL and all it returns is an empty String (ie nothing between the last thing you typed and the EOL).