Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop does not execute the first command after 2nd 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 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.

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

like image 979
PhoonOne Avatar asked Feb 19 '23 19:02

PhoonOne


2 Answers

Due to the fact that

input.next()

does not consume newline characters, these get passed passed back to your loop and does not allow a value to be entered. You would 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.

like image 156
Reimeus Avatar answered Feb 21 '23 10:02

Reimeus


When you use a Scanner with System.in, data isn't read from System.in until a newline (you've hit Enter). So what you actually have in the Scanner's buffer is:

Jake\nL\nV\nD\n

The key here is that D doesn't get sent to the Scanner's buffer until you've pressed enter. That's why there's that \n at the end. Normally, when you're calling input.next(), that previous stray newline gets gobbled up. But when you call input.nextLine() the second/third time around the for loop, it's reading that stray trailing newline:

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

So you get a blank line, essentially reading everything between the D and \n, which is nothing.

You need to call nextLine() each time and call charAt(0) on the resulting String.

like image 22
Jon Lin Avatar answered Feb 21 '23 09:02

Jon Lin