Need help with java while loop

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sammyboy78
    New Member
    • Jun 2007
    • 21

    #1

    Need help with java while loop

    I'm trying to create a program that continuously asks for user input until the user inputs "stop" for employee name which will terminate the program. I have compiled the following code but when the program runs through the second time it skips the user input for the employee name and goes directly to number of hours worked. What am I doing wrong?

    // Weekly pay calculator
    // This program will calculate weekly pay amount for an employee when given hours worked and rate of pay
    import java.util.Scann er;

    public class Pay2
    {
    //main method
    public static void main( String args[])
    {
    //create Scanner for obtaining inputs from user
    Scanner input = new Scanner( System.in );

    double hours; //hours worked
    double rate; // rate of pay
    String employeeName; //name of worker
    double pay; // product of hours and rate
    String stop;

    boolean empName = false;

    while ( !empName )
    {

    System.out.prin tf( "Enter employee name: " ); //prompt
    employeeName = input.nextLine( ); //read employee name from user
    System.out.prin tln();

    if(employeeName .equals("stop") )
    {empName = true;
    }
    else
    {empName = false;
    }

    System.out.prin tf( "Enter hours worked by %s : ", employeeName ); //prompt
    hours = input.nextDoubl e(); //read hours worked
    System.out.prin tln();

    System.out.prin tf( "Enter rate of pay for %s :$", employeeName ); //prompt
    rate = input.nextDoubl e();//read rate of pay
    System.out.prin tln();

    pay = hours * rate; //multiply hours times rate to get weekly pay

    System.out.prin tf( "Employee name: %s \nWeekly pay amount: $%.2f", employeeName, pay); //display name and pay amount
    System.out.prin tln();
    } //end while
    } //end main

    } //end class
  • dmjpro
    Top Contributor
    • Jan 2007
    • 2476

    #2
    Originally posted by sammyboy78
    I'm trying to create a program that continuously asks for user input until the user inputs "stop" for employee name which will terminate the program. I have compiled the following code but when the program runs through the second time it skips the user input for the employee name and goes directly to number of hours worked. What am I doing wrong?

    // Weekly pay calculator
    // This program will calculate weekly pay amount for an employee when given hours worked and rate of pay
    import java.util.Scann er;

    public class Pay2
    {
    //main method
    public static void main( String args[])
    {
    //create Scanner for obtaining inputs from user
    Scanner input = new Scanner( System.in );

    double hours; //hours worked
    double rate; // rate of pay
    String employeeName; //name of worker
    double pay; // product of hours and rate
    String stop;

    boolean empName = false;

    while ( !empName )
    {

    System.out.prin tf( "Enter employee name: " ); //prompt
    employeeName = input.nextLine( ); //read employee name from user
    System.out.prin tln();

    if(employeeName .equals("stop") )
    {empName = true;
    }
    else
    {empName = false;
    }

    System.out.prin tf( "Enter hours worked by %s : ", employeeName ); //prompt
    hours = input.nextDoubl e(); //read hours worked
    System.out.prin tln();

    System.out.prin tf( "Enter rate of pay for %s :$", employeeName ); //prompt
    rate = input.nextDoubl e();//read rate of pay
    System.out.prin tln();

    pay = hours * rate; //multiply hours times rate to get weekly pay

    System.out.prin tf( "Employee name: %s \nWeekly pay amount: $%.2f", employeeName, pay); //display name and pay amount
    System.out.prin tln();
    } //end while
    } //end main

    } //end class

    It is most probably because of unread enter(next line) character.

    Kind regards,
    dmjpro.

    Comment

    • r035198x
      MVP
      • Sep 2006
      • 13225

      #3
      Originally posted by sammyboy78
      I'm trying to create a program that continuously asks for user input until the user inputs "stop" for employee name which will terminate the program. I have compiled the following code but when the program runs through the second time it skips the user input for the employee name and goes directly to number of hours worked. What am I doing wrong?

      // Weekly pay calculator
      // This program will calculate weekly pay amount for an employee when given hours worked and rate of pay
      import java.util.Scann er;

      public class Pay2
      {
      //main method
      public static void main( String args[])
      {
      //create Scanner for obtaining inputs from user
      Scanner input = new Scanner( System.in );

      double hours; //hours worked
      double rate; // rate of pay
      String employeeName; //name of worker
      double pay; // product of hours and rate
      String stop;

      boolean empName = false;

      while ( !empName )
      {

      System.out.prin tf( "Enter employee name: " ); //prompt
      employeeName = input.nextLine( ); //read employee name from user
      System.out.prin tln();

      if(employeeName .equals("stop") )
      {empName = true;
      }
      else
      {empName = false;
      }

      System.out.prin tf( "Enter hours worked by %s : ", employeeName ); //prompt
      hours = input.nextDoubl e(); //read hours worked
      System.out.prin tln();

      System.out.prin tf( "Enter rate of pay for %s :$", employeeName ); //prompt
      rate = input.nextDoubl e();//read rate of pay
      System.out.prin tln();

      pay = hours * rate; //multiply hours times rate to get weekly pay

      System.out.prin tf( "Employee name: %s \nWeekly pay amount: $%.2f", employeeName, pay); //display name and pay amount
      System.out.prin tln();
      } //end while
      } //end main

      } //end class
      1.) Please use code tags when posting code
      2.) Use input.next(); instead of input.nextLine( ) for reading the name.
      3.) Exit the loop when stop is entered otherwise the program probably continues to take in details for an employee named stop!

      Comment

      • sammyboy78
        New Member
        • Jun 2007
        • 21

        #4
        Ok I've made some suggested changes and it works great. Thanks for the help! Now I have a problem that when I run the program, if I enter a one word name (John) it executes perfectly but if I enter a two word name such as John Smith I get this error message:

        C:\Documents and Settings\Sam>ja va Pay2
        Enter employee name: John Smith

        Enter hours worked by John : Exception in thread "main" java.util.Input MismatchE
        xception
        at java.util.Scann er.throwFor(Sca nner.java:840)
        at java.util.Scann er.next(Scanner .java:1461)
        at java.util.Scann er.nextDouble(S canner.java:238 7)
        at Pay2.main(pay2. java:32)

        Here is my revised code:

        Code:
        // Weekly pay calculator
        // This program will calculate weekly pay amount for an employee when given hours worked and rate of pay
        import java.util.Scanner;
        
        public class Pay2
        {
        	//main method
        	public static void main( String args[])
        	{
        		//create Scanner for obtaining inputs from user
        		Scanner input = new Scanner( System.in );
        
        		double hours; //hours worked
        		double rate; // rate of pay
        		String employeeName; //name of worker
        		double pay; // product of hours and rate
        		String stop;
        
        		boolean empName = true;
        
        		while ( empName )
        			{
        
        			System.out.printf( "Enter employee name: " ); //prompt
        			employeeName = input.next(); //read employee name from user
        			System.out.println();
        
        			if( ! (employeeName.equals("stop")))
        			   {
        
        				System.out.printf( "Enter hours worked by %s : ", employeeName ); //prompt
        				hours = input.nextDouble(); //read hours worked
        				System.out.println();
        
        				System.out.printf( "Enter rate of pay for %s :$", employeeName ); //prompt
        				rate = input.nextDouble();//read rate of pay
        				System.out.println();
        
        				pay = hours * rate; //multiply hours times rate to get weekly pay
        
        				System.out.printf( "Employee name: %s \nWeekly pay amount: $%.2f", employeeName, pay); //display name and pay amount
        				System.out.println();
                       }
        				else
        				{
        				  empName = false;
        				}
        			}//end while
        
        	} //end main
        
        } //end class

        Comment

        • JosAH
          Recognized Expert MVP
          • Mar 2007
          • 11453

          #5
          Originally posted by sammyboy78
          Ok I've made some suggested changes and it works great. Thanks for the help! Now I have a problem that when I run the program, if I enter a one word name (John) it executes perfectly but if I enter a two word name such as John Smith I get this error message: <snip>
          That's the trouble with scanners: they do exactly what you've told them to do;
          when you're just a *bit* off, they crash in a most horrible way.

          Basically you want to read a name (or two, three? names) for an employee
          followed by a double representing the number of working hours followed by
          the payment rate. Lets handle the tree input parts one by one:

          1) one or more names are best read on a single line; the nextLine() method
          is best for it; it also reads the <newline> character for you.

          2) when you want to read a double value and the user types "foobarbaz" the
          scanner will crash (as you have painfully noticed). A Scanner class also has
          a 'hasDouble()' method which checks if the next input makes up a valid double.

          3) when you have sucessfully read a double number the <newline> character
          hasn't been read yet (it wasn't part of that double number).

          To keep things simple for now I'd suggest you use 'nextLine()' for the names,
          and 'nextDouble()' for the numbers; use a 'nextLine() method again after you've
          read the last double for the current employee, that enables the scanner to
          read *another* entire line for the name(s) of the next employee. the 'nextLine()'
          following the last 'nextDouble()' reads away that <newline> character that was
          still unread and obstiptated the input buffer. (that's why it seemed it skipped
          reading a next name in your original attempt).

          kind regards,

          Jos

          Comment

          • sammyboy78
            New Member
            • Jun 2007
            • 21

            #6
            Thnk you! I changed my input.next() to input .nextLine() and also added a nextLine() statement after my last nextDouble() and it works perfectly! You guys are a Godsend! Thanks a lot! Now to program for only positive inputs for hours and rate...

            Comment

            Working...