0

I am very new to Java and am taking my first Java class at the moment. I'm trying to add up an array that takes user input and not simply just filling in the array with predetermined numbers. Would the code to get the sum of the the array be the same as a predetermined array? Here is the code that I have.

import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
 int[] monthSales = new int[12];
 String[] monthNames = new String[12];
 monthNames[0] = "January";
 monthNames[1] = "February";
 monthNames[2] = "March";
 monthNames[3] = "April";
 monthNames[4] = "May";
 monthNames[5] = "June";
 monthNames[6] = "July";
 monthNames[7] = "August";
 monthNames[8] = "September";
 monthNames[9] = "October";
 monthNames[10] = "November";
 monthNames[11] = "December";
 int i = 0;
 while (i <= 11) 
 {
 System.out.println("What was the sales for the month of " + monthNames[i] + ": ");
 monthSales[i] = scan.nextInt();
 i++;
 } 
}
}
asked Mar 8, 2015 at 16:48
1
  • You can iterate over monthSales in a for-loop and add the value of each element into another variable. Commented Mar 8, 2015 at 16:52

3 Answers 3

2

Two ways to sum the array:

1) In Java 8 you can do (assuming the array is called "monthSales"):

int sum = IntStream.of(monthSales).sum();
System.out.println("The sum is " + sum);

2) alternatively you can also do:

int sum = 0;
for (int i : monthSales)
 sum += i;
answered Mar 8, 2015 at 16:54
0

Yes do it simply like:

int sum = 0;
for (int i=0; i<monthSales.length; i++)
 sum += monthSales[i];

Note aside:

Make use of for loop instead of while which would be much readable, generic and use i < monthNames.length instead of i <= 11

answered Mar 8, 2015 at 16:52
0

Just iterate through your array and add the value to a variable

int sum = 0;
for(int value: monthSales)
 sum += value;
answered Mar 8, 2015 at 16:55

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.