简体   繁体   English

Java创建直方图方法有人可以帮助我理解这段代码吗?

[英]Java creating histogram method can someone help me to understand this code?

`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));
    
}

} ` I wrote this and some of the parts I looked at from google and other sources but I couldn't understand the else part in public static int[] histogram ` 我写了这个以及我从谷歌和其他来源查看的一些部分,但我无法理解 public static int[] histogram 中的 else 部分

` else `否则

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

` How does this newArr[count] ++; ` 这个 newArr[count] ++ 是怎么做的; works can someone explain to me, please作品有人可以向我解释,请

` How does this newArr[count] ++; ` 这个 newArr[count] ++ 是怎么做的; works can someone explain to me, please作品有人可以向我解释,请

Two thins are happening on this one line.这条线上正在发生两件事情。

  1. We get the reference to value in position count from newArr array.我们从newArr数组中获取对位置count的引用。
  2. We increment it by 1.我们将其增加 1。

Therefore if you have array newArr = [1,2,3] calling newArr[0]++ would result in you having the following state of newArr as [2,2,3] .因此,如果您有数组newArr = [1,2,3]调用newArr[0]++将导致您具有以下newArr状态为[2,2,3] newArr [2,2,3]

If something is still unclear, respond with a comment to this answer.如果仍有不清楚的地方,请对此答案发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM