File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Loop gone wrong Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Loop gone wrong" Watch "Loop gone wrong" New topic

Loop gone wrong

Wolfgang Obi
Ranch Hand

Joined: Dec 05, 2005
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...



marc weber

Joined: Aug 31, 2004
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 ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
samir Sadiki
Ranch Hand

Joined: Apr 22, 2006
Posts: 31

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!: " );

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

System.out.print("What is your " +i+ ". integer?: " );
int zahl = IM.readInt();


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("The average is: " +result2 );
Wolfgang Obi
Ranch Hand

Joined: Dec 05, 2005
Posts: 134
@Marc: that's a helpful hint!
@Samir: thanx alot for the corrections!

thanx guys,....
great help.

I agree. Here's the link:
subject: Loop gone wrong
It's not a secret anymore!