// Week 3 Checkpoint1: Payroll Program Part 2
// Due May 04, 2012
// Created by: Kennith Adkins
import java.util.Scanner;
public class Assignment1
{
public static void main ( String[] args )
{
Scanner input = new Scanner(System.in);
// Variables
String employeeName = null;
int hours;
double rate;
double pay;
while ( employeeName != "stop")
{
// Request information from user
System.out.print ( "Employee Name: ");
employeeName = input.nextLine();
System.out.print ( "Hourly Rate: ");
rate = input.nextDouble();
System.out.print ( "Number of Hours worked this week: ");
hours = input.nextInt();
// Calculate pay
pay = rate * hours;
// Display information
System.out.printf ("%s will get paid $%.2f this week.\n", employeeName, pay);
}
}
}
When I run the program it runs fine. When it hits the loop and repeats, Employee Name: and Hourly Rate seem to bunch up. Also how would I get it to immediately stop after typing stop as employee Name?
As this appears to be a homework question I’ll point you in a learning direction.
So for the employee name question I will redirect you to How do I compare strings in Java?
The scrunching issue is because when you reenter the loop and call scanner(input).nextLine it ends up actually reading the input text that it had not seen yet. So one option is to switch to something else lick a BufferedReader or move the scanner deceleration down in to the loop.More research
I haven’t worked much with the scanner class and after seeing this I was somewhat confused. The issue is actually the nextInt and nextDouble. They dont claim the return charter and as such when you call next line next time it is picking up the leftover return character.
So my option of reseting the scanner when reentering works in this specific case but you should either use 2 scanners or move off of scanners.