gpt4 book ai didi

java - 我需要显示每列的最小值,编号不均匀。列数

转载 作者:太空宇宙 更新时间:2023-11-04 13:32:24 27 4
gpt4 key购买 nike

public class SmallestColumn2{
public static void main(String[] args){
int [][] smallest = new int [][]{{17,70,97,-20},{27,73},{84,80,40,280},{90,98,58,-48,104}};
System.out.println("Smallest per column");
for(int col = 0; col < 5; col++){
int least = smallest[0][col];
for(int r = 0; r < 4; r++){
if (smallest [r][col] < least){
least = smallest[r][col];
}
}
System.out.println("Column " + col + ":" + least);
}
}
}

最佳答案

我猜它会抛出ArrayIndexOutOfBoundsException

我会使用条件来避免这种情况:

if(col>=smallest[r].length) //continue the loop
continue;

我会将least变量设置为尽可能高的值:

int least = Integer.MAX_VALUE;

避免异常

整个代码

public class SmallestColumn2{
public static void main(String[] args){
int [][] smallest = new int [][]{{17,70,97,-20},{27,73},{84,80,40,280},{90,98,58,-48,104}};
System.out.println("Smallest per column");
for(int col = 0; col < 5; col++){
int least = Integer.MAX_VALUE;
for(int r = 0; r < smallest.length; r++){
if(col>=smallest[r].length) //continue the loop
continue;
if (smallest [r][col] < least){
least = smallest[r][col];
}
}
System.out.println("Column " + col + ":" + least);
}
}
}

为了使其更加动态,我将硬编码的 4 重写为数组的长度。数字 5 应该计算为所有数组的最大长度数,而不仅仅是硬编码的 5

注意:未经测试

关于java - 我需要显示每列的最小值,编号不均匀。列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32044851/

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