Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Loop gone wrong

Wolfgang Obi
Ranch Hand
Posts: 134
Hi can someone please tell me what I've done wrong in this programme....
the code seems to be okay, but the output is a bit faulty....

I'd really appreciate...

Thx

-W.O.

marc weber
Sheriff
Posts: 11343
The problem is with this segment of code:

To see what's happening here, suppose the int 5 is input and assigned to zahl. Then...

newZahl is 5.
newZahl is 10. (This just adds newZalh to itself.)
result1 is 10. (Supposedly a cumulative sum?)
result2 is 1. (Supposedly an average?)

Hint: Try describing exactly what you want to do in English before writing the Java code. For example, "I want to take the input number and add it to a cumulative total."
[ April 26, 2006: Message edited by: marc weber ]

Ranch Hand
Posts: 31
Hi

You are in the right path, just try these minor changes

public class sumAverage {
public static void main(String [] args){

int newZahl=0;
float result1 = 0;
float result2 = 0;

System.out.println("Please enter 10 Integers one by one and press [ENTER] after each entry!: " );
System.out.println();

for(int i=1; i<=10; i++){

System.out.print("What is your " +i+ ". integer?: " );

System.out.println();

newZahl= zahl; //number enterd by the user
//newZahl +=newZahl; get rid of this line
result1 += newZahl; //the cumulative sum

}
result2 = result1/10; //once you've added all the numbers you can compute the average

System.out.println("The sum is: " +result1 );
System.out.println();
System.out.println("The average is: " +result2 );
System.out.println();
System.out.println();
}
}

Wolfgang Obi
Ranch Hand
Posts: 134