我是 Java 初学者,我试图找出为什么我的方法没有返回输入数组中的最大值。我的想法是,当调用该方法时,for 循环将搜索数组的每个值。然后它开始将第一个值设置为最大值,任何大于该值的值都会成为此后的最大值。
非常感谢任何帮助!
public double displayLargest (double[][] l) {
for (int x=0; x < l.length-1; x++) {
for (int y=0; y < l[x].length; y++) {
double w = l[0][0];
if (w < l[x][y]) {
x++;
y++;
w = l[x][y];
maxValue = w;
}
}
}
System.out.println("The largest value in the array is: " + maxValue);
return maxValue;
}
最佳答案
以下方法将返回 double
的 2D 输入数组中的最大值,如果不存在值,则返回 null
。
public Double displayLargest(double[][] l){
Double maxValue = null;
for (int x=0; x < l.length; x++) {
for (int y=0; y < l[x].length; y++) {
if (maxValue == null || maxValue < l[x][y]) {
maxValue = l[x][y];
}
}
}
System.out.println("The largest value in the array is: " + maxValue);
return maxValue;
}
关于java - 返回数组中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35471446/