Java:关于最小位置矩阵的一些错误
这就是我所做的Java:关于最小位置矩阵的一些错误,java,Java,这就是我所做的 java.util.Scanner input = new java.util.Scanner(System.in); System.out.print("Rnter the number if rows and columns of the array: "); int row = input.nextInt(); int col = input.nextInt(); double numList[][]
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Rnter the number if rows and columns of the array: ");
int row = input.nextInt();
int col = input.nextInt();
double numList[][] = new double[row][col];
System.out.println("Enter the array:");
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
numList[i][j] = input.nextDouble();
}
}
int[] location;
location = locateSmallest(numList);
System.out.println("The location of the smallest element is at " + Arrays.toString(location));
}
public static int[] locateSmallest(double[][] a){
int i, j;
double minNum = a[0][0];
int minNumLocate[] = new int[2];
for (j = 0; j < a.length; j++){
for (i =0; i < a[j].length; i++){
if (a[j][i] < minNum){
minNumLocate[j] = j;
minNumLocate[i] = i;
}
}
}
return minNumLocate;
}
但是我输入了双输入,它出现了错误,就像这里一样
Enter the number if rows and columns of the array: 3 4
Enter the array:
1 2 3 4
3 4 5 6
3 4 5 6
The location of the smallest element is at [0, 0]
Enter the number if rows and columns of the array: 3 4
Enter the array:
1.5 3 2 10
3.5 4 2 1
35 44 5.5 9.6
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 2
我不知道应该在哪里更正它,请帮我检查一下,
如果可能的话,请帮我检查一下,在同一时间,我在哪里可以改进得更清楚
谢谢大家
a[j]。长度将为3,int minNumLocate[]
等于2。所以j或i的值低于2,没有什么可保护的
只需更改在minNumLocate分配上定义索引的方式:
int minNumLocate[] = new int[2];
for (j = 0; j < a.length; j++){
for (i =0; i < a[j].length; i++){
if (a[j][i] < minNum){
minNumLocate[1] = j;
minNumLocate[0] = i;
}
}
}
最后一个优化是使用输入中的列
和行
值
int minNumLocate[] = new int[2];
minNUm = a[0][0];
for (j = 0; j < row ; j++){
for (i =0; i < col; i++){
if (a[j][i] < minNum){
minNumLocate[1] = j;
minNumLocate[0] = i;
minNUm = a[j][i];
}
}
}
int minNumLocate[]=new int[2];
minNUm=a[0][0];
对于(j=0;j|
谢谢你的建议,错误已经解决了,但是输出仍然有一点问题,在我检查后,它应该发生在你给我建议的同一部分。我发现尝试了几个输入,它有正确的位置作为值,但我输入这也是3 x 4矩阵code
23.5 35 2 10 4.5 3 45 3.5 35 44 5.5 9.6code
,最小值应该是2,它是正确的,位置应该是[0,3],但输出是[2,3],其他部分是否有任何可能的问题,在嵌套循环内添加打印以查看索引和值比较。我更新了帖子,尝试重新使用行和列输入变量重新计算大小。非常感谢,我终于实现了我的目标。欢迎。你能接受我的回答吗@蒋迪基
int minNumLocate[] = new int[2];
minNUm = a[0][0];
for (j = 0; j < row ; j++){
for (i =0; i < col; i++){
if (a[j][i] < minNum){
minNumLocate[1] = j;
minNumLocate[0] = i;
minNUm = a[j][i];
}
}
}