import java.util.Scanner; public class Lab3 { // Get sum of all numbers in array method public static int getSum(double[][] list) { list = new double[4][4]; int sum = 0; int r,c = 0; for (r = 0; r < list.length; r++) for (c = 0; c < list[r].length; c++) sum += list[r][c]; return sum; } // Input data method public static double[][] getData(double[][] list) { Scanner input = new Scanner(System.in); double[][] data = new double[list.length][list[0].length]; int r,c = 0; double num = 0; for (r = 0; r < data.length; r++) for (c = 0; c < data[r].length; c++) num = input.nextDouble(); data[r][c] = num; return data; } // Main method public static void main(String[] args) { System.out.println("Enter a 4-by-4 matrix row-by-row:"); double[][] numList = new double[4][4]; double[][] newList; newList = getData(numList); int sum = getSum(newList); System.out.println("Sum of the matrix is " + sum); } }
When i try running the program I get this :
Enter a 4-by-4 matrix row-by-row: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at Lab3.getData(Lab3.java:25) at Lab3.main(Lab3.java:36)
Any help will be much appreciated as this has given me a headache...