[英]I can't input values higher than 9 into this
I think this works perfectly when I input values lower than 9. But whenever I input a value higher than 9, program throws ArrayIndexOutOfBoundsException. 我认为当我输入的值小于9时,这是完美的。但是,当我输入的值大于9时,程序将引发ArrayIndexOutOfBoundsException。 I cant figure out which causes this problem.
我不知道是什么引起了这个问题。 Can someone simply explain me this problem and what is the solution for this?
有人可以简单地向我解释这个问题,对此有什么解决方案?
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;
}
}
The isUnique
array has size 10, instead it should be sized by the largest integer that has been inserted by the user. isUnique
数组的大小为10,而应由用户插入的最大整数确定大小。
Of course, there are better ways to check for duplicate numbers of arbitrary size, like using a Set<Integer>
. 当然,还有更好的方法来检查任意大小的重复数字,例如使用
Set<Integer>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.