Need help with Arrays in Java. I am getting an error and do not know how to fix it! Will post code below!
public class ArrayPrinter { public static void main(String[] args) { int [] oneD = {5, 6, 7, 8 }; int[][] twoD = {{2, 4, 6, 8}, {8, 7, 9, 1}, {3, 5, 1, 2}}; int[][] twoD2 = {{1, 2}, {3, 4, 5}, {6}, {7, 8, 9}}; printArray(oneD); printArray(twoD); System.out.println("]"); System.out.println(" "); printArray(twoD2); } public static void printArray(int[] arr) { System.out.print("["); int size = arr.length; for (int i = 0; i < size; i++) { System.out.print(arr[i]); if (i < size -1){ System.out.print(", "); } } System.out.println("]"); } public static void printArray(int[][] arr) { System.out.println("[ "); for (int row = 0; row <= arr.length; row++){ System.out.print(""); for (int i = 0; row <= arr[row].length; i++) { printArray(arr[i]); } } } }
Here is what I get when I run the program: [5, 6, 7, 8] [ [2, 4, 6, 8] [8, 7, 9, 1] [3, 5, 1, 2] Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at ArrayPrinter.printArray(ArrayPrinter.java:53) at ArrayPrinter.main(ArrayPrinter.java:19) I do not know how to fix it and I have been trying figure it out. I do online school and I e-mailed my teacher but she is not getting back to me and this is due today or I will get behind! I am literally pulling my hair out! PLEASE HELP!!!!!!! @SapphireMoon
printArray(int[][] arr) is using a variable "row" in nested for loops. That will cause wierd results (errors). A two dimensional array by nature has rows and columns, x, y coordinates to refer to a single item.
Thank you very much! THat helped me out a lot and the error is fixed after changing my code.
h
@BlazeRyder
Join our real-time social learning platform and learn together with your friends!