swydell
swydell

Reputation: 2020

Display sum from array with 5 indices

This is a very simple application in which I declare an array containing 5 elements. I use an enhanced for loop to iterate the length of the array. I imported a Scanner object for user input for next number, then I calculate the sum. But the sum displays 0, which is not what the application is suppose to output. Here is the application: //application to create an array that will hold 5 indices and ask user input for each index number then //calculate and 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 the array

        int sum = number[0];//initialize sum to array index 0
        System.out.print("Enter number: " );//prompt for user input
        for (int i:number)//uses enhanced for loop
        {
           number[i] = input.nextInt();//reads input
           if(i<number.length)//evaluates condition
           {
           System.out.print("Enter next number: ");//prompt for next input number

           }else
           sum += number[i];//initializes sum to number array

          }//end enhanced for loop
       System.out.println("\nThe sum is " +sum);
 }//end method main

 }//end class FindSum

Upvotes: 0

Views: 1183

Answers (2)

Matt Jones
Matt Jones

Reputation: 509

Just update sum in your as the user enters values:

    System.out.print("Enter next number: ");//prompt for next input number
    sum += input.nextInt();

You code currently is only putting the last number you enter (5th number) into the array as the previous numbers are getting erased.

Your for loop need to be a normal for loop in order to update your array. Currently, i will ALWAYS be 0 as your array is initialized with 0's when it is created. Therefore, each time the for loop is invoked, it will use 0 for i. So, the else statement will never run and it will just keep putting the current value the user enters in the 0th position.

By the end, you should have a for-loop like:

for (int i = 0; i < number.length; i++)//uses enhanced for loop
{
    System.out.print("Enter next number: ");//prompt for next input number
    number[i] = input.nextInt();//reads input

    sum += number[i];//initializes sum to number array

 }//end enhanced for loop

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

Change your enhanced for loop to a regular for loop,

for (int i = 0; i < number.length; i++)

The issue is number only contains 0 so each iteration of the loop assigns 0 to i. Also, you need to remove your logic

// if(i<number.length)//wouldn't be in loop body if condition weren't true.
// {
System.out.print("Enter next number: ");//prompt for next input number
// }else
sum += number[i];//add number to sum.

Upvotes: 3

Related Questions