简体   繁体   中英

Java 2D array sum (addition of all)

I want to sum a 2D array to this:

I want the method to sum a 2D array. However, if x is greater than y the program gets an exception. I tried to debug it, but I do not know how to fix it smoothly. Should I create another method if x is greater than y ? Points is the array with all the values.

 int x = //Random value
 int y = //Random value
 deltSum = new int[y];

 int output = 0;
 for (int t = 0; t < x; t++) {
    for (int i = 0; i < y; i++) {
        output += points[t][i]; //Add all values in the first section of the array.
    }
    deltSum[t] = output;
    System.out.println(output);
    output = 0;
 }

Try to assign values of x and y as below:

int x = points.length;
int y = points[].length;
deltSum = new int[y];

Understand that if the Random values are out of the index of point[][] array, then it will surely give you runtime exceptions.

If you want random values then use Random Class within the range of length of the array to get different and random values of x and y and avoid ArrayIndexOutOfBound exception.

import java.util.Random; //to use Random Class...

...

Random randomGenerator = new Random(); //making instance of Random

//these statements will assign a value to x & y that is random 
//and smaller than the maximum length which is specified.
int x = randomGenerator.nextInt(points.length); //Will assign random value to x less then points.length
int y = randomGenerator.nextInt(points[0].length); ////Will assign random value to x less then points[].length

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM