当我输入低于9的值时,我认为这非常有效。但是每当我输入一个大于9的值时,程序都会抛出ArrayIndexOutOfBoundsException。我无法弄清楚导致这个问题的原因。有人可以简单地解释一下这个问题,解决方法是什么?
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
int[][] twoDAarray = new int[3][3];
Scanner input = new Scanner(System.in);
System.out.println("Enter values: ");
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
twoDAarray[i][j] = input.nextInt();
}
}
System.out.println(checkLoShuSquare( twoDAarray ));
}
public static boolean checkLoShuSquare( int[][] twoDAarray ) {
boolean[] isUnique = new boolean[twoDAarray.length*twoDAarray[0].length+1];
for ( int i = 0; i < twoDAarray.length; i++ ) {
for ( int j = 0; j < twoDAarray[0].length; j++ ) {
if ( isUnique[twoDAarray[i][j]] ){
return false;
}
isUnique[twoDAarray[i][j]] = true;
}
}
int[] lessThan9 = new int[twoDAarray.length*twoDAarray[0].length+1];
for ( int i = 0; i < twoDAarray.length; i++ ) {
for ( int j = 0; j < twoDAarray[0].length; j++ ) {
if (lessThan9[twoDAarray[i][j]] <= 9){
return true;
}
}
}
return true;
}
}
isUnique
数组的大小为10,而应使用用户插入的最大整数来调整大小。
当然,有更好的方法来检查任意大小的重复数字,例如使用Set<Integer>
。