Reputation: 51
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++;
}
}
}
Upvotes: 0
Views: 119
Reputation: 3275
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;
Upvotes: 2
Reputation: 5712
Just iterate through your array and add the value to a variable
int sum = 0;
for(int value: monthSales)
sum += value;
Upvotes: 0
Reputation: 37023
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
Upvotes: 0