I’m trying out several exercises from a Java programming book. I have the code below:
import java.io.*;
import java.util.Scanner;
public class Ex420
{
public static void main( String args[] )
{
String employeeName = "";
double workHours,excessHours, hourlyRates, grossPay;
Scanner input = new Scanner( System.in );
while ( employeeName != "stop" )
{
System.out.printf( "\nInput employee name or stop to exit: " );
employeeName = input.nextLine();
System.out.printf( "Input working hours: " );
workHours = input.nextDouble();
System.out.printf( "Input hourly rates: " );
hourlyRates = input.nextDouble();
if ( workHours <= 40 & workHours >= 0 )
{
excessHours = 0;
grossPay = hourlyRates * workHours;
System.out.printf( "%s's gross pay is $%.2f\n", employeeName, grossPay );
}
else if ( workHours > 40 )
{
excessHours = workHours - 40;
grossPay = hourlyRates * 40 + 1.5 * hourlyRates * excessHours;
System.out.printf( "\n%s's worked for %.1f excess hours.\n", employeeName, excessHours );
System.out.printf( "%s's gross pay is $%.2f\n", employeeName, grossPay );
}
else
{
System.out.printf( "Invalid input. Please try again." );
}
} // end while
} // end main
} // end class Ex420
The problem is, the while loop doesn’t seem to be working. Whenever I input “stop” as the employeeName, the program just goes on. I tried replacing “stop” with any other String and it still doesn’t work. But when I try initializing employeeName with “stop”, the program quits right away, which is expected. What am I doing wrong here?
Furthermore, after the first loop, the program always skips asking the employeeName. I tried replacing employeeName = input.nextLine(); with employeeName = input.next(); and it doesn’t skip it anymore. I’m wondering though, is there any way I can make it not skip the input when using employeeName = input.nextLine();?
Thanks in advance for the help!
I’m guessing it’s because the
!=test you use in thewhileloop compares strings for reference equality. That is, when it makes a comparison, it’s not just testing to see whether the strings have the same sequence of characters; it checks to see if they are the exact same object. But when theScannercreates aStringto contain the text it read from standard input, thatStringis not going to be the same object as the string literal"stop"in your code. They’re two objects that just happen to have the same content, but they exist at different locations in memory, so!=treats them as being unequal.Solution: start your loop like this instead: