题:
给定一个口袋妖怪名称的String数组:

 String[] pokemon={"Bulbsaur","Squirtle","Weedle","Pidgey","Rattata"};


a)使用WHILE循环,编写代码以显示神奇宝贝名称,如下所示

输出:

拉塔塔

皮吉

杂草

松鼠

Bulbsaur

(按上述顺序)

然后,我还要尝试以下问题:

public static void main(String[] args) {
    String[] pokemon= {"Bulbsaur","Squirtle","Weedle","Pidgey","Rattata"};
    int i=0;
    while(i<pokemon.length) {
        System.out.println(pokemon[i]);
        i++;
    }

}


我只想知道如何像输出顺序一样排列值。我知道我可以改变立场,但是我不认为这个问题可以改变。

谢谢你的帮忙!

最佳答案

只需反向迭代数组并打印:

String[] pokemon= {"Bulbsaur","Squirtle","Weedle","Pidgey","Rattata"};
int i = pokemon.length - 1;
while (i >= 0) {
    System.out.println(pokemon[i--]);
}


如果您实际上需要颠倒Pokemon数组中的顺序,那么我建议进行就地交换:

String[] pokemon= {"Bulbsaur","Squirtle","Weedle","Pidgey","Rattata"};
int len = pokemon.length;
for (int i=0; i < pokemon.length/2; ++i) {
    String temp = pokemon[i];
    pokemon[i] = pokemon[len-1-i];
    pokemon[len-1-i] = temp;
}

10-07 18:23