Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with "while" in Java

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!

like image 585
bow Avatar asked Jun 26 '10 02:06

bow


People also ask

What is the disadvantage of while loop?

Disadvantages of while loop: While loop can cause the problem if the index length is incorrect. It is also slow as the compiler adds the runtime code to perform the conditional check on every iteration through this loop.

Why is my while statement not working?

The while loop is not run because the condition is not met. After the running the for loop the value of variable i is 5, which is greater than three. To fix this you should reassign the value before running the while loop (simply add var i=1; between the for loop and the while loop).

What are the problems while using while loop?

while loop. The potential risks and errors can be divided into two broad categories: problems with the loop control (running the loop wrong number of times), and problems with the loop actions (producing the wrong output).

Why is my while loop not breaking Java?

The issue with your while loop not closing is because you have an embedded for loop in your code. What happens, is your code will enter the while loop, because while(test) will result in true . Then, your code will enter the for loop. Inside of your for loop, you have the code looping from 1-10.


3 Answers

When comparing strings in Java use equals method, not == or != operators. By using those operators you simply compare references to objects and not their contents. So your condition should look like

while ( !"stop".equals(employeeName) )

Note the that "stop" is first because theoretically your employeeName variable can be null. This way the code is not going to throw NullPointerException by calling equals method on the null object.

like image 167
Eugene Ryzhikov Avatar answered Oct 06 '22 01:10

Eugene Ryzhikov


I'm guessing it's because the != test you use in the while loop 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 the Scanner creates a String to contain the text it read from standard input, that String is 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:

while (!"stop".equals(employeeName)) {
like image 38
David Z Avatar answered Oct 06 '22 00:10

David Z


The problem is you're not using the right structure and you need to use equals() not == to compare Strings. The basic structure you want is:

System.out.printf("\nInput employee name or stop to exit: ");
String employeeName = input.nextLine();
while (!employeeName.equals("stop")) {
  ...
  System.out.printf("\nInput employee name or stop to exit: ");
  employeeName = input.nextLine();
}

Basically you need to check if the user entered "stop" immediately and the above does that. Your version doesn't.

On a side note, try and adopt Java coding conventions including spacing and curly brace placement.

like image 25
cletus Avatar answered Oct 05 '22 23:10

cletus