Issue
Hey everyone or whoever is reading this :),
I received a task which deals with 2d-arrays, where I determined the numbers of a 3x3 array, then gave them to another method ("calculation").At the end the program is supposed to tell you whether in one of the three lines there are the same numbers (yes = true, no = false). However, when I run the program that is written on the console:
1 2 3 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 at Test.main(Test.java:14)
Can someone tell me what to do or what I did wrong??
public class Test {
public static void main(String[] args) {
boolean Result;
int[][] field = {
{
1, 3, 2
},
{
2, 2, 2
},
{
3, 1, 3
}
};
Result = Calculation(field);
for (int i = 0; i < field.length; i++) {
for (int j = 0; j < field[i].length; i++) {
System.out.println(field[i][j]);
}
System.out.println();
}
if (Result == true) {
System.out.println(Result + "One line is filled with the same numbers.");
} else {
System.out.println(Result + "No line is filled with the same numbers.");
}
}
public static boolean Calculation(int[][] field) {
if (field[0][0] == 1 & field[0][1] == 1 & field[0][2] == 1) {
return true;
} else if (field[1][0] == 1 & field[1][1] == 1 & field[1][2] == 1) {
return true;
} else if (field[2][0] == 1 & field[2][1] == 1 & field[2][2] == 1) {
return true;
} else if (field[0][0] == 2 & field[0][1] == 2 & field[0][2] == 2) {
return true;
} else if (field[1][0] == 2 & field[1][1] == 2 & field[1][2] == 2) {
return true;
} else if (field[2][0] == 2 & field[2][1] == 2 & field[2][2] == 2) {
return true;
} else if (field[0][0] == 3 & field[0][1] == 3 & field[0][2] == 3) {
return true;
} else if (field[1][0] == 3 & field[1][1] == 3 & field[1][2] == 3) {
return true;
} else if (field[2][0] == 3 & field[2][1] == 3 & field[2][2] == 3) {
return true;
} else {
return false;
}
}
}
Solution
Simple ! Imagine a list with a, b, c
index of a is 0 because in java list index begin with 0, therefore c index is 2, but the lenght of list is 3 but the first index is 0 you know ?
Ok now the problem look
for (int i = 0; i < field.length; i++) {
for (int j = 0; j < field[i].length; i++) {
System.out.println(field[i][j]);
}
System.out.println();
}
In the second loop you use i++ while I think you wanted to put "j++"
Answered By - PastaLaPate
Answer Checked By - David Marino (JavaFixing Volunteer)