我无法在此输入高于 9 的值
I can't input values higher than 9 into this
我认为当我输入小于 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>
.
我认为当我输入小于 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>
.