理解代码有一点问题

时间:2014-04-11 16:50:42

标签: java arrays string sorting int

我有非常不寻常的要求,我希望我可以请你提供专业的反馈。我对以下一段代码有一点了解。

代码:

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

我很感激有人可以一步一步地将它分解给我,看看我是否理解正确!

(我对int ref部分感到困惑,是否有必要?我从我用来学习java的书中拿出了以下代码,但是他们在那里放了很多令人困惑的行...)

干杯!

1 个答案:

答案 0 :(得分:2)

ref在循环体中定义为与ref = indeks[y];对应。鉴于先前对indeks [1,3,0,2]的定义,它将输出islands(注意小写“i”)

Fiji
Kozumel
Bermudy
Azory

所以,把它们放在一起

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

哪些输出(当我运行时) -

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