The condition inside the
if statement is not a
boolean but reassigns the String "theName" to the variable "Stop" which if undeclared will result in a compile error "cannot find symbol".
Use the
equals method to test for String equality. The "==" operator does not do well for testing String equality.
The semi–colon following the
if statement counts as an empty statement and will cause the code inside the following curley braces to be skipped.
So change it to look lie this
if(theName.equals("Stop"))
{
The next question is: what happens if the user types in "stop" instead of "Stop"?
Part 1
import java.util.Scanner;
public class PayrollRx
{
public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
int hoursWorked;
int hourlyPayRate;
int weeklyPay;
System.out.print ( "Enter employee name: " );
String theName = input.nextLine();
// Does this class have methods yet?
// If so you would not refer to them this
// way inside the main method.
// Payroll.setEmployeeName( theName );
System.out.print( "Enter hours worked: " );
hoursWorked = input.nextInt();
System.out.print( "Enter hourly pay rate: " );
hourlyPayRate = input.nextInt();
// multiply hours worked * hourly pay rate
weeklyPay = hoursWorked * hourlyPayRate;
// display employee name and weekly pay total
System.out.printf( "Employee Name: %s, Weekly pay is $%d%n",
theName, weeklyPay );
}
}
Part 2
import java.util.Scanner;
public class PayrollRx
{
public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
boolean enterMoreData = true;
while(enterMoreData)
{
System.out.print ( "Enter employee name: " );
String theName = input.nextLine();
if(theName.equalsIgnoreCase("stop"))
{
input.close();
break;
}
int hoursWorked;
do
{
System.out.println("Enter hours worked: ");
String line = input.nextLine();
hoursWorked = Integer.parseInt(line);
if(hoursWorked < 0)
System.out.println("number must be positive");
}
while(hoursWorked < 0);
int hourlyPayRate;
do
{
System.out.println("Enter hourly pay rate: ");
String line = input.nextLine();
hourlyPayRate = Integer.parseInt(line);
if(hourlyPayRate < 0)
System.out.println("number must be positive");
}
while(hourlyPayRate < 0);
// multiply hours worked * hourly pay rate
int weeklyPay = hoursWorked * hourlyPayRate;
// display employee name and weekly pay total
System.out.printf( "Employee Name: %s, Weekly pay is $%d%n",
theName, weeklyPay );
}
}
}