簡體   English   中英

使用增強的 For 循環遍歷數組並將每個項目添加到輸出變量

[英]Using an enhanced For loop to loop through array and add each item to the output variable

所以我必須創建一個 pokedex 程序來顯示文件中的 pokemon 數量,同時它還顯示文件中的所有 pokemon。 我添加了該文件,這里其他類中的所有內容都是指向我的 GitHub 的鏈接,其中顯示了其他類及其代碼。 我的主要問題是編寫 For 循環來顯示所有 pokemon 的計數和結果。 這是我到目前為止所擁有的。

public class Pokedex implements PokedexInterface {
private Pokemon pokedex[] = new Pokemon[1000];
private int pokemonCount = 0;

@Override
public String toString() 
 {
    // loop through pokedex
     // add each item of the pokedex to the output variable
     String output = new String();
     for(Pokemon count : pokedex)
     {
        output += count;
     }
    return output;

    }

public void addPokemon(Pokemon pokemon) {
}
}

再次這里是 整個程序鏈接

@Override
public String toString() {
    int pokemonCount = 0;
    StringBuilder result = new StringBuilder();
    for (Pokemon pokemon : pokedex) {
        pokemonCount++;
        result.append(pokemon.toString());
    }
    return new StringBuilder("Pokemon Count: ").append(pokemonCount).append("\n\n").append(result).toString();

StringBuilder是將許多不同的字符串添加在一起的最佳選擇,就像您對所有 Pokemon 所做的一樣。 這段代碼首先找出有多少口袋妖怪。 然后,它使用增強的 for 循環將 Pokemon 的所有 String 表示形式添加到一個字符串中,然后與 pokemon 計數一起返回。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM