0

Help needed with array code

Question: Create a two dimensional array of integers called rows[][] with five rows and four Columns. Modify the array so that the last element in each row is equal to the sum of all the elements in the row minus the last element. Initialize rows[][] with data any way you choose and print out the modified array. My code so far: import java.util.Arrays; public class Aeeay { public static void main(String[] args) { int[] array = { {1,2} {3,4} }; int sum = 0; //for-loop to iterate through the whole array index by index. for(int i = 0; i < array.length - 1; i++){ sum += array[i]; } array[array.length-1] = sum; System.out.println(sum); System.out.println(Arrays.toString(array)); } public static int[] lastElemSum(int[] myArray) { // returns a COPY of the input array, and leaves the input array unchanged //to extract 1d array from 2d for(int[] oneDim : myArray) { // process oneDim System.out.println(Arrays.toString(oneDim)); } }

5th Jul 2022, 6:28 PM
Adebiyi Itunuayo
Adebiyi Itunuayo - avatar
2 Respuestas
5th Jul 2022, 6:33 PM
Adebiyi Itunuayo
Adebiyi Itunuayo - avatar
0
Adebiyi Itunuayo Your 2d array declaration is wrong.. Missing camma, and a [] Correct way is: int[][] array = { {1,2},{3,4} }; And you need 2 nested loops.. Outer loop should pass current total row. Inner can go through all column elements of current row.. Like for i = 0 to array.length for j=0 to array[i].length-1 array[i][j] is current element. You are missing an closing brace } at end of class... edit: you are not using lastElementSum() method, you don't it actually.. use it or remove.. Hope it helps to correct your code...
5th Jul 2022, 6:47 PM
Jayakrishna 🇮🇳