Need help with simple repetition statement
I cannot seem to understand why after the first round of input, the loop continues before the name variable is entered the second time. After the loops completes once, I get this output:
Enter the employee's name: Enter the employee's wage:
here is the code....
Code java:
package payroll;
import java.util.Scanner;
public class Payroll {
public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
String name;
double wage;
int hours;
double pay;
System.out.print( "Welcome to the Payroll Calculator\n\n" );
System.out.print( "Enter the employee's name: " );
name = input.nextLine();
while (name.compareTo("stop") != 0 )
{
System.out.print( "Enter the employee's wage: " );
wage = input.nextDouble();
System.out.print( "Enter the number of hours worked: " );
hours = input.nextInt();
pay = wage * hours;
System.out.printf( "\n\nName: %s\nWage: $%.2f\nHours worked: %d\nPay: $%.2f\n", name, wage, hours, pay );
System.out.print( "Enter the employee's name: " );
name = input.nextLine();
}
}
}
Re: Need help with simple repetition statement
I think your problem could be with how the Scanner class works. It reads the line when you type in something and press Enter and saves all of it in a buffer, including the end-line character. When you call nextInt() the method returns the data you entered and leaves the end-line character in the buffer.
You need to call the nextLine() method to read the end-line out of the buffer after you call the nextInt().
It is possible to type many data values on a line before you press Enter and have nextInt() read them one by one until it gets to the end-line character.
With your current program try entering the wage and the hours worked and the next name all on the same line before pressing Enter and see what happens.