Reputation: 29
i am creating a program that create a 2D matrix using java it suppose to build a 2D array after it check if the numbers are prime or no.
i know that the error is in the for loop of the createMatrix Function and i hope that someone can help me and explain where is my error and how to fix it.
the system display this error :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at test6.test6.createMatrix(Question6.java:26)
at test6.test6.main(Question6.java:52)
package test6;
public class test6 {
public static int isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return 1;
}
if (number % 2 == 0) {
return 0;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return 0;
}
}
return 1;
}
public static int[][] createMatrix(int[][] m) {
int i, j;
for (i = 0; i < m[0].length; i++) {
for (j = 0; j < m.length; j++) {
System.out.println(m[i][j]);
}
}
return m;
}
public static String toString(int[][] m) {
StringBuilder text = new StringBuilder();
for (int row = 0; row < m.length; row++) {
int r[] = m[row];
for (int col = 0; col < r.length; col++) {
if (col > 0)
text.append(", ");
text.append(r[col]);
}
text.append("\n");
}
return text.toString();
}
public static void main(String[] args) {
int[][] num = new int[][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
System.out.println(toString(createMatrix(num)));
}
}
Upvotes: 0
Views: 67
Reputation: 70959
You are transversing your m X n
array n times down the m direction and m times down the n direction.
As a result, within createMatrix(...)
you run a good chance of walking out of the array (unless it is a square array). Also, createMatrix
is a horrible name for something that just prints out a matrix created elsewhere.
Upvotes: 1
Reputation: 421280
You've swapped the indexes the other way around:
for (i = 0; i < m[0].length; i++) { // i runs over the columns of first row
for (j = 0; j < m.length; j++) { // j runs over the rows
System.out.println(m[i][j]); // here i is the row, and j is the column!
}
}
A better way to loop over the matrix is:
for (i = 0; i < m.length; i++) { // let i run over the rows
for (j = 0; j < m[i].length; j++) { // let j run over the columns
System.out.println(m[i][j]);
}
}
Upvotes: 4