Click to See Complete Forum and Search --> : While loop for Java


Reddy001
12-10-2007, 03:13 AM
Khalid,

This is the code I've written so far. This is a payroll program, that ask for input information of employee...name, hourly rate, hours for the week. Once this is input, the program will sum the weekly rate. However, I had to modify the program so that the employee name is equal to stop using a while loop. Here's the program that I've written so far;

//create Scanner to obtain input from command window
Scanner input = new Scanner(System.in);

String name;//employee name
int number1;//first number to multiply
int number2;//second number to multiply
int sum;//product of number1 and number2

while ("Enter Name\n" !="stop")
//employee weekly pay();


System.out.println("Enter Name\n");//prompt employee name
name = input.nextLine();//read employee name

System.out.println("Enter Hourly rate");//prompt hourly rate
number1 = input.nextInt();//read hourly rate


System.out.println("Hours for the Week:");//prompt hours worked for the week
number2 = input.nextInt();//read hours worked

sum = number1 * number2;//multiply numbers


System.out.printf("Sum is %d\n", sum);//display sum





}//end method main

}//end class multiplication

ed81
12-10-2007, 07:50 AM
If anyone could help me, I would be greatful. I'm currently taking a class for Java, and we built a program that would ask for emplyee name, hourly rate, and hours worked for the week. Once we did this the application would talley the weekly pay. Now we have to modify this program to use so that it uses the while loop until the employee name is equal to stop. Can anyone help?

Ok, so let me see if I understand what you want to do, You want the program so that when the user inputs a string "stop" it will stop asking for employee names..? am I right?

mdjo
12-10-2007, 04:30 PM
Hmm, the literal "Enter name" is never going to equal the literal "Stop", so the loop will always promptly exit.

Perhaps what you have in mind is something like:


while (true)
{
String name=input.nextLine();
if (name.equals("stop"))
break;
... etc ...
}


or if you want to be more concise (and hard to read ...)


String name;
while (!(name=input.nextLine()).equals("stop"))
{
... etc ...
}