write a method convertTo2D that takes three parameters- a 1D array, an int for row size…
- User
write a method convertTo2D that takes three parameters- a 1D array, an int for row size and and an int for column size. The method should then take the 1D array and plug in the values to the appropriate locations and return a 2D array. There are mulitple ways of doing it, being familiar with the different ways will help you as this is a common array algorithm!
Test your method with multiple inputs to make sure it works correctly. public class MyProgram { public static void main(String[] args) {
}}
- Assistant
- User
don't use exceptions?
- Assistant
- User
what are the errors in my code public class MyProgram { public static void main(String[] args) { int [] oneDArray = {69,69,69,69,69,69,69}; int [][] convertedArray = convertTo2D(oneDArray, 6, 9); print2DArray(convertedAray); } } public static int[] convertTo2D(int[] oneDArray, int rowSize, int colSize) { int [][] twoDArray = new int[rowSize][colSize]; int arrayIndex = 0; for (int row = 0; row < rowSize && arrayIndex < oneDArray.length; row++) { for(int col = 0; col < colSize && arrayIndex < oneDArray.length; col++){ twoDArray[row][col] = oneDArray[arrayIndex++]; } } return twoDArray; } public static void print2DArray(int [][] array) { for (int [] row : array) { for(int value : row) { System.out.print(value + " "); } System.out.println(); } }
- Assistant