java - Display sum from array with 5 indices -
this simple application in declare array containing 5 elements. utilize enhanced loop iterate length of array. imported scanner object user input next number, calculate sum. sum displays 0, not application suppose output. here application: //application create array hold 5 indices , inquire user input each index number //calculate , display sum of indices in console window.
import java.util.scanner; public class findsum { public static void main (string [ ] args) { scanner input = new scanner(system.in); int [ ] number = new int [ 5]; // instantiate array int sum = number[0];//initialize sum array index 0 system.out.print("enter number: " );//prompt user input (int i:number)//uses enhanced loop { number[i] = input.nextint();//reads input if(i<number.length)//evaluates status { system.out.print("enter next number: ");//prompt next input number }else sum += number[i];//initializes sum number array }//end enhanced loop system.out.println("\nthe sum " +sum); }//end method main }//end class findsum
change enhanced for
loop regular for
loop,
for (int = 0; < number.length; i++)
the issue number
contains 0
each iteration of loop assigns 0
i
. also, need remove logic
// if(i<number.length)//wouldn't in loop body if status weren't true. // { system.out.print("enter next number: ");//prompt next input number // }else sum += number[i];//add number sum.
java arrays
No comments:
Post a Comment