【问题标题】:I need to display the smallest value per column w/ uneven no. of columns我需要显示每列带有不均匀编号的最小值。列数
【发布时间】:2015-08-17 07:26:20
【问题描述】:
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);
        }
    }
}

【问题讨论】:

  • 您的代码是如何工作的以及您的期望是什么?
  • 应该显示每列的最小值

标签: java multiple-columns


【解决方案1】:

我猜它会抛出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

注意:未测试

【讨论】:

  • 运行:每列最小列 0:17 列 1:70 列 2:40 线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 4 在 SmallestColumn2.main(SmallestColumn2.java:6) 列3:-48 Java 结果:1 BUILD SUCCESSFUL(总时间:0 秒)
  • 非常感谢老兄!我们在这里欢呼雀跃xD
  • 老兄每列最大呢?
  • 哥们,你是最棒的!你能在菲律宾时间周一下午 2:00 - 5:00 帮助我吗?xD
猜你喜欢
  • 1970-01-01
  • 2017-07-23
  • 2020-06-23
  • 2014-07-23
  • 1970-01-01
  • 2021-10-13
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
相关资源
最近更新 更多