【问题标题】:Java creating histogram method can someone help me to understand this code?Java创建直方图方法有人可以帮助我理解这段代码吗?
【发布时间】:2021-11-07 11:29:52
【问题描述】:
public class Library {
    
    public static int[] histogram(int a[],int M) {
        int[] newArr = new int[M];
        
        //Fill the new array
        try {
        if(a.length<M)
            System.out.println("Array lenght should be "
                    + "bigger than the number");
        else
            
            for(int i = 0; i < a.length; i++){
                int count = a[i];
                
                newArr[count] ++;
            }
        
        }
        catch (Exception e) {
            // TODO: handle exception
            System.out.println(e.getMessage());
        }
        
        //return the array
        return newArr;
    }
    
    public void printArray(int s[]) {
        int position = 0;
        for (int i = 0; i < s.length; i++) {
            System.out.print(position+" ");
            position++;
        }
        System.out.println();
        
        for (int i = 0; i < s.length; i++) {
            System.out.print(s[i]+" ");
        }
    }
    
    
    
    public static void main(String[] args) {
        
        Library l1 = new Library();
        
        int J = 5;
        int[] w = {1,2,0,1,2,3};
        
        l1.printArray(histogram(w,J));
        
    }
}

我写了这个以及我从谷歌和其他来源看到的一些部分,但我无法理解 public static int[] histogram 中的 else 部分

        else
            
            for(int i = 0; i < a.length; i++){
                int count = a[i];
                
                newArr[count] ++;
            }

这个 newArr[count] ++;有人可以给我解释一下吗

【问题讨论】:

    标签: java eclipse histogram


    【解决方案1】:

    ` 这个 newArr[count] ++;有人可以给我解释一下吗

    这一行发生了两件事。

    1. 我们从 newArr 数组中获取对位置 count 的值的引用。
    2. 我们将其增加 1。

    因此,如果您有数组 newArr = [1,2,3] 调用 newArr[0]++ 将导致您具有以下 newArr 状态为 [2,2,3]

    如果仍有不清楚的地方,请对此答案发表评论。

    【讨论】:

    • 是的,我明白了,谢谢,您能否向我解释一下for(int i = 0; i &lt; a.length; i++){ int count = a[i]; 部分,因为计数值将等于第一个值,即 1,因为 int[] w = {1,2,0,1,2,3};那么代码中发生了什么
    • 那么直方图向我们展示了什么?它显示了特定值在测量中出现的频率。我们将测量值保存到 count 变量中...然后 newArr[count] 包含有关我们看到特定值的频率的信息,因此我们将值加一
    • 是的,它实际上有很大帮助,所以'count'实际上保护了 a[i] 的值,假设为 0,如果 a[4] 等于 count,则数组中的第一个变量再次它会 newArr[count]++ 并更新我们的 newArr[] 然后它会移动到 a[1] 然后是 a[2],等等。
    • 好东西。如果您的问题得到解决,请随时接受并投票。这可以帮助其他人找到并重复使用它。
    猜你喜欢
    • 1970-01-01
    • 2020-11-03
    • 2015-07-14
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 2021-12-24
    相关资源
    最近更新 更多