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[][] = 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;
}
}
总的来说,应该为 int 输入完成,就像这里
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].length
将是 3 并且int minNumLocate[]
暗淡等于 2。所以没有什么可以保护 j 或 i 低于 2。
只需更改您在 minNumLocate assignment 上定义索引的方式:
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;
}
}
}
此外,缺少minNum
找到的最小值的更新。
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;
minNUm = a[j][i];
}
}
}
最后一次优化,将使用输入中的col
和row
值
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];
}
}
}
推荐阅读
- java - 奇怪的问题。是否有 Java 命令可以从您自己的 Javadoc 中读取信息?
- angular - isAuthenticated 值未更新且路由未发生
- sql-server - 检查另一个表中的特定值作为约束
- javascript - 为什么我不能在threejs中使用OrbitControls类
- filter - 如何根据多对一关系的值过滤 DirectUS 集合的记录?
- swift - 我希望我的代码在后台连续/同步运行(DispatchQueue)
- django - 使用实例数据预填充 Django 表单 ChoiceField
- swift - 如何在 didBegin 联系函数中更改 SKShapeNode 的 fillColor?
- python - Pandas 中的三次插值引发 ValueError:边界处的导数数量不匹配:预期 2,得到 0+0
- python - 无法执行脚本,因为在 Python 中找不到模块