473,411 Members | 2,030 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,411 software developers and data experts.

Need help with java while loop

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.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 = false;

while ( !empName )
{

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

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

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();
} //end while
} //end main

} //end class
Jun 2 '07 #1
5 5051
dmjpro
2,476 2GB
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.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 = false;

while ( !empName )
{

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

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

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();
} //end while
} //end main

} //end class

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

Kind regards,
dmjpro.
Jun 2 '07 #2
r035198x
13,262 8TB
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.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 = false;

while ( !empName )
{

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

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

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();
} //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!
Jun 2 '07 #3
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>java Pay2
Enter employee name: John Smith

Enter hours worked by John : Exception in thread "main" java.util.InputMismatchE
xception
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextDouble(Scanner.java:2387)
at Pay2.main(pay2.java:32)

Here is my revised code:

Expand|Select|Wrap|Line Numbers
  1. // Weekly pay calculator
  2. // This program will calculate weekly pay amount for an employee when given hours worked and rate of pay
  3. import java.util.Scanner;
  4.  
  5. public class Pay2
  6. {
  7.     //main method
  8.     public static void main( String args[])
  9.     {
  10.         //create Scanner for obtaining inputs from user
  11.         Scanner input = new Scanner( System.in );
  12.  
  13.         double hours; //hours worked
  14.         double rate; // rate of pay
  15.         String employeeName; //name of worker
  16.         double pay; // product of hours and rate
  17.         String stop;
  18.  
  19.         boolean empName = true;
  20.  
  21.         while ( empName )
  22.             {
  23.  
  24.             System.out.printf( "Enter employee name: " ); //prompt
  25.             employeeName = input.next(); //read employee name from user
  26.             System.out.println();
  27.  
  28.             if( ! (employeeName.equals("stop")))
  29.                {
  30.  
  31.                 System.out.printf( "Enter hours worked by %s : ", employeeName ); //prompt
  32.                 hours = input.nextDouble(); //read hours worked
  33.                 System.out.println();
  34.  
  35.                 System.out.printf( "Enter rate of pay for %s :$", employeeName ); //prompt
  36.                 rate = input.nextDouble();//read rate of pay
  37.                 System.out.println();
  38.  
  39.                 pay = hours * rate; //multiply hours times rate to get weekly pay
  40.  
  41.                 System.out.printf( "Employee name: %s \nWeekly pay amount: $%.2f", employeeName, pay); //display name and pay amount
  42.                 System.out.println();
  43.                }
  44.                 else
  45.                 {
  46.                   empName = false;
  47.                 }
  48.             }//end while
  49.  
  50.     } //end main
  51.  
  52. } //end class
Jun 2 '07 #4
JosAH
11,448 Expert 8TB
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
Jun 2 '07 #5
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...
Jun 2 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Dominique | last post by:
I am trying to communicate to a prolog server from a java client, however even though the connection is successfully made every time I try to perform QueryExecute I get an error, either Socket...
1
by: banjo123 | last post by:
Dear java.help: I just started learning java and was trying to compile some java sourc from the Javascript World Submission webpage. I know I have loaded m JDK successfully since I can compile...
10
by: pcbutts1 | last post by:
Yes this is a homework assignment. My instructor has broken english and I just could not follow along last night. How do I do this Write the program in Java (without a graphical user interface)...
0
by: south622 | last post by:
I'm taking a beginning Java course and I'm stuck in week eight of a nine week course. If anyone could help me I would greatly appreciate it. This assignment was due yesterday and each day I go past...
6
crystal2005
by: crystal2005 | last post by:
Hello guys, I'm a beginner in Java application programming. I started to write a Java application in which link to MS Access database. I encountered a problem in deletion function. E.g. I would...
4
by: chellemybelle | last post by:
Hello, I basically have made a little cheezy slideshow and would like to add captions to each pic as it loops through. I've tried everything I can think of. I'm assuming I might need to use an...
1
by: saytri | last post by:
I have a problem with this code. I'm, doing a quiz, and the questions are stored in a binary file. My problem is how am i going to compare the answers entered by the user to the correct answers. The...
1
by: tikney5 | last post by:
I need to modify my current program so that is uses a class to store and retrieve the employees name, hourly rate, and number of hourse worked. Use a constructor to initialize the employee...
3
by: 100grand | last post by:
Modify the Inventory Program to use a GUI. The GUI should display the information one product at a time, including the item number, the name of the product, the number of units in stock, the price...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.