简体   繁体   中英

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

` else

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

` How does this newArr[count] ++; works can someone explain to me, please

` How does this 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.
  2. We increment it by 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] .

If something is still unclear, respond with a comment to this answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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