Reputation: 2785
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: https://i.sstatic.net/eb1BA.jpg
Upvotes: 4
Views: 1262
Reputation: 1
I had a similar problem, and this helped me. declare this outside the loop:
boolean ranOnce=false;
then inside the loop declare this
if(!ranOnce){ranOnce=true;String s=input.nextLine();}
Upvotes: 0
Reputation: 143886
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.
Upvotes: 3
Reputation: 159784
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.
Upvotes: 3
Reputation: 1365
Replace your input.next()'s with input.nextLine()'s. That should fix it.
Upvotes: 2