This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
total in loops
Posted by Ally Wood on August 01, 2000 at 2:07 AM
In my loop I want to add the integers from my array up, the compiler says that sum is an undefined variable. However if I Put in -- int sum = 0 then I'm not getting the sum of these integers only the last integer at the end of the loop. How can I get around this?? From Ally Wood redally@iname.com (new InputStreamReader (System.in)) ; for (int no = 0 ; no < numbers.length; no++) { System.out.println(" Enter the integer " + (no+1)) ; System.out.print(no + 1) ; System.out.print(":") ; numbers[no] = Integer.parseInt(stdin.readLine( ) ) ; sum += numbers[no]; } // can't define varible sum if (no == numbers.length - 1) System.out.println("The Sum is: " + sum) ; } My code is (Above) is trying to add integers from an array to sum. However the compiler says sum varible is not declared. If I add-- int sum = 0 --I'm not getting all the integers only the last. if I just add--int sum--it says it is not initialised.How can I around this?
Replies:
|