aspose file tools*
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
Author

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...

Thx

-W.O.

marc weber
Sheriff

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
sscce.org
samir Sadiki
Ranch Hand

Joined: Apr 22, 2006
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?: " );
int zahl = IM.readInt();

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

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

thanx guys,....
great help.

-W.O.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Loop gone wrong
 
Similar Threads
two public classes in a file
bad programming style??- (getter/setter methods )
Puzzled
Apply function names as parameters in other functions
Rounding a Double...to the nearest Integer, Tenths place, Hundredths place, etc..