The problem of “while” in Java

I'm trying a few exercises in the Java programming book I have the following code:

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",excessHours );
    System.out.printf( "%s's gross pay is $%.2f\n",grossPay ); 
   }
   else
   {
    System.out.printf( "Invalid input. Please try again." );
   }  
  } // end while
 } // end main
} // end class Ex420

The problem is that the while loop doesn't seem to work Whenever I enter "stop" as the employeename, the program continues I tried to replace stop with any other string and it still didn't work However, when I try to initialize employeename with "stop", the program will exit immediately, which is expected What did I do wrong here?

In addition, after the first loop, the program always skips asking employeename I tried to replace employeename = input nextLine(); with employeeName = input. next(); It no longer skips it I wonder if there is any way for me to use employeename = input Do not skip input when nextline();?

Thank you for your help!

Solution

I guess this is because you use it in the while loop= Test compare strings for reference equality That is, when it compares, it doesn't just test to see if the string has the same character sequence; It checks whether they are identical objects However, when scanner creates a string containing the text it reads from standard input, the string will not be the same as the object of the string text "stop" in the code They are two objects with exactly the same content, but they exist in different locations in memory, so= Treat them as unequal

Solution: start your cycle instead:

while (!"stop".equals(employeeName)) {
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>