Home > Enterprise >  How do I print the sum of an array's elements?
How do I print the sum of an array's elements?

Time:04-20

I've written a program, where the user gives input on how many elements they want their array to have. However, I am unable to print the sum of those elements.

Here's my code:

import java.util.*;
public class sumOfArrayValues {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter array size here: ");
        int size = input.nextInt();
        System.out.println();

        int[] myArray = new int[size];

        Random rand = new Random();
        int limit = 101;

        System.out.print("Array: ");
        for (int i = 0; i < myArray.length; i  ) {
            myArray[i] = rand.nextInt(limit);
            System.out.print(myArray[i]   " ");
            System.out.println();

        }

        int sum = 0;

        for (int i : myArray) {
            sum  = 1;
        }
        System.out.println("The sum of the array elements is: "   sum);
    }
}

If there are any other tips to make my code less verbose, please don't hesitate to let me know.

CodePudding user response:

If there are any other tips to make my code less verbose, please don't hesitate to let me know.

Scanner input = new Scanner(System.in);
System.out.print("Please enter number of elements to sum: ");
int size = input.nextInt();

Random r  = new Random();
// generate a stream of `size` values between 0 and 100 inclusive
// and sum them
int sum = r.ints(size,0,101).sum();

System.out.println("sum = "   sum);

CodePudding user response:

You probably want to add i to the sum if you want the sum of all the elements. Right now sum reflects the size of myArray because you only add 1 for every element in the array.

for (int i : myArray) {
    sum  = i;
}

CodePudding user response:

tl;dr

Streams tend to make brief code

ThreadLocalRandom.current().ints( 0 , 101 ).limit( arraySize ).toArray()

… and …

IntStream.of( randomInts ).sum()

Streams

You asked:

any other tips to make my code less verbose

Streams are another way to write brief code. The IntStream class is for a stream of integer values.

ThreadLocalRandom is a random-number generator that is automatically instantiated one per thread. You can use the class even if not spawning threads. The class has many handy methods. Here we use the ints method to generate a stream of random numbers. We then collect those into an array of int values.

int[] randomInts = ThreadLocalRandom.current().ints( 0 , 101 ).limit(7).toArray();

We can dump those to console.

System.out.println( Arrays.toString( randomInts )   );

[41, 54, 54, 20, 91, 80, 50]

And we can calculate the sum of those int values by creating another IntStream.

int sum = IntStream.of( randomInts ).sum();

sum = 390

See that code run live at IdeOne.com.

  •  Tags:  
  • java
  • Related