我的矩阵代码在多行中给出以下错误,我无法理解为什么。我会欢迎任何帮助。我一直有错误,数组索引越界异常。我的方法有什么问题或者我怎么能抓住这个例外?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at mb.Mb.swap(Mb.java:65)
at mb.Mb.randomiseRow(Mb.java:56)
at mb.Mb.main(Mb.java:121)
以下是我的代码:
package mb;
import java.util.*;
public class Mb {
/**
* @param args the command line arguments
*/
public static int[][] createMatrix(int size)
{
int[][] boardMatrix = new int[size][size];
return boardMatrix;
}
public static void print(int[][] board)
{
for(int i = 0; i<board.length; i++)
{
for(int j = 0; j<board[i].length; j++)
{
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
public static int[] singleRow(int size, int startValue)
{
int[] row = new int[size];
for(int i = 0; i<row.length; i++)
{
row[i] = i + startValue;
}
return row;
}
public static void randomiseRow(int[] board)
{
Random rnd = new Random();
int randX = 0;
int randY = 0;
for(int x = 0; x<board.length; x++) //no of rows
{
swap(board, x, (rnd.nextInt(board.length)+1));
}
}
public static void swap(int[] board, int a, int b)
{
int temp = board[a];
board[a] = board[b];
board[b] = temp;
}
public static boolean compareArray(int[] board1, int[] board2)
{
if(board1.length != board2.length)
{
return false;
}
for(int i = 0; i<board1.length; i++)
{
if(board1[i] == board2[i])
{
return false;
}
}
return true;
}
public static boolean compare2DArray(int[] board1, int[][] board2, int startValue, int endValue)
{
for(int i = startValue; i<endValue; i++)
{
if(!compareArray(board1, board2[i]))
{
return false;
}
}
return true;
}
public static void main(String[] args) {
// TODO code application logic here
int userInput = 0;
System.out.print("Matrix size: ");
Scanner scn = new Scanner(System.in);
userInput = scn.nextInt();
while(userInput < 0 && userInput > 9)
{
System.out.println("Invalid matrix size. Re-enter ");
userInput = scn.nextInt();
}
int[][] matrixBoard = new int[userInput][userInput];
createMatrix(userInput);
for(int i = 1; i<userInput; i++)
{
matrixBoard[0] = singleRow(userInput, 1);
do{
randomiseRow(matrixBoard[i]);
}while(!compare2DArray(matrixBoard[i], matrixBoard, 0, i));
}
print(matrixBoard);
}
}