gpt4 book ai didi

java - ArrayIndexOutofBounds——有帮助吗?

转载 作者:行者123 更新时间:2023-12-01 17:34:27 27 4
gpt4 key购买 nike

问题出在int [][]tam = new int [a][b]处。就只有那一条线。我是 Java 新手,有 C++ 背景。

//"Exercitiul" 3
Scanner input = new Scanner(System.in);//instructiune scanner
DataInputStream dis4 = new DataInputStream(System.in);
DataInputStream dis5 = new DataInputStream(System.in);
String st1 = null;
String st2 = null;
try{
System.out.println("Introduceti numarul de Randuri");
st1 = dis4.readLine();
System.out.println("Introduceti numarul de Coloane");
st2 = dis5.readLine();
}

catch (IOException ioe) {
ioe.printStackTrace();
}

int a = Integer.parseInt(st1);
int b = Integer.parseInt(st2);

int [][]tam = new int[a][b];

System.out.println("Verificare " + tam[a][b]);
System.out.println("Introduceti Elementele Matricei ");

for (int m=0 ; m < tam.length ; m++)
for (int n=0 ; n < tam[i].length ; n++){

tam[m][n] = input.nextInt();//instructiune scanner
}

System.out.println("Matricea A: ");
for (int m=0 ; m < tam.length ; m++)
{ System.out.println();
for (int n=0 ; n < tam[i].length ; n++)
System.out.print(tam[m][n]+" ");
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Program.main(Program.java:95)

最佳答案

如果是数组a长度n ,元素为a[0]通过a[n-1] 。就您而言,您分配了 tam作为int[a][b]矩阵右下角的元素是 tam[a-1][b-1] .

我认为你想要m作为内循环中的索引 for (int n=0 ; n < tam[i].length ; n++)而不是i .

关于java - ArrayIndexOutofBounds——有帮助吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7869380/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com