...

View Full Version : Loops problem



skylit
09-26-2011, 02:47 AM
I am doing practice problems for class (not homework), and I've gotten most of the coding down except for one stipulation. The exercise reads:

"Write a program that reads input of the number of hours an employee has worked and displays the employee's total and average (per day) number of hours.
The company doesn't pay overtime, so cap any day at 8 hours.

Sample Run:
How many days? 3
Hours? 6
Hours? 12
Hours? 5
Employee's total paid hours = 19
Employee’s average paid hours = 6.3333333"

I can't figure out how to include the bolded stipulation.
I've tried adding:

if ( sum >8 ) {
sum = 8;
}

but I know that isn't right, and I can't think of any other solution. Can someone advise me on my work?



public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);
System.out.println("How many days worked? ");
int count = keyboard.nextInt();
int i = 1;
int sum = 0;

while (i <= count) {
System.out.println("Hours? ");
sum += keyboard.nextInt();
i++;

}

System.out.println("Employee's total paid hours= " +sum);
System.out.println("Employee's average paid hours= " +(double)sum/count);




}
}



Also! If anyone can explain to me why there has to be an initialization of " int sum = 0 ", that would be great. I just know I have to include it for this loop.

Old Pedant
09-26-2011, 03:28 AM
This is the javaSCRIPT forum.

Your code is written in JAVA.

About the only thing the two languages have in common is the first 4 letters of their names.

*********

Having said that:

In Java (not in JavaScript) *all* variables must be both declared and initialized.

So your variable sum has to be declared and initialized *SOME PLACE* in your code.

And that must be done *OUTSIDE* the loop because inside the loop you are just adding on to what is already there.

But as for the other part of the problem: Easy.

Don't just add the hours worked onto the sum!

*FIRST* assign it to a separate variable. Then use if to find out if it is more than 8 and, if so, change it to 8.

Only *after* doing that do you add that value to sum.

Don't be afraid to use more variables. They don't cost extra, honest.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum