简体   繁体   中英

Having a little issue understanding the code

I have quite unusual request and i hope i can ask you for professional feedback. I have a little problem understanding following piece of code.

Code:

Class TestTablic {
    public static void main(String[] args) {
      int [] indeks = new int[4];  
      indeks[0] = 1;
      indeks[1] = 3;
      indeks[2] = 0;
      indeks[3] = 2;
      String[] islands = new String[4];  
      Islands[0] = "Bermudy";
      Islands[1] = "Fiji";
      Islands[2] = "Azory";
      Islands[3] = "Kozumel";
      int y = 0;
      int ref;
      while (y < 4) {
        ref = indeks[y];
        System.out.print("Island = ");
        System.out.println(Islands[ref]);
        y = y + 1;
  }
 }
}

I'd appreciate someone who could break it down step by step to me to see if i understood it correctly!

(I'm mostly puzzled about the int ref part, is it even neccessary? I took the following code from the book i use to learn java but they put a lot of confusing lines in there...)

Cheers!

The ref is defined in the body of the loop as corresponding to ref = indeks[y]; . Given the previous definition of indeks [1, 3, 0, 2] it will output the islands (note lower case "i")

Fiji
Kozumel
Bermudy
Azory

So, bringing it all together

public static void main(String[] args) {
    int[] indeks = new int[4];
    indeks[0] = 1;
    indeks[1] = 3;
    indeks[2] = 0;
    indeks[3] = 2;
    String[] islands = new String[4];
    islands[0] = "Bermudy";
    islands[1] = "Fiji";
    islands[2] = "Azory";
    islands[3] = "Kozumel";
    int y = 0;
    int ref;
    while (y < 4) {
        ref = indeks[y];
        System.out.print("Island = ");
        System.out.println(islands[ref]);
        y = y + 1;
    }
}

Which outputs (when I run it) -

Island = Fiji
Island = Kozumel
Island = Bermudy
Island = Azory

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