-3

So I have to create a pokedex program that displays the number of pokemon in the file while it also displays all the pokemon in the file. I added the file and everything in my other class here is the link to my GitHub which shows the other classes and the code for them. My main problem is writing the For Loop on displaying the count and result for all the pokemon. Here is what I have so far.

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) {
}
}

Again here is the link to the whole program

1 Answers1

0
@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();

A StringBuilder is the best option for adding many different strings together like you are doing with all the Pokemon. This code first finds how many pokemon there are. Then, it uses an enhanced for loop to add all the String representations of the Pokemon together into one string which is then returned along with the pokemon count.

SizableShrimp
  • 666
  • 7
  • 12
  • The first loop could be replaced by `pokedex.length`, but since `pokedex` is a fixed-size array, there might need to be checks to count used entries. – Ken Y-N Jan 28 '19 at 01:07
  • A `List` would be better in this situation but they are already using an array. With a list, they could just do `pokedex.size()` to get the number of pokemon. You can't use `pokedex.length` as the array is always a length of `1000` regardless if values are `null` or not. – SizableShrimp Jan 28 '19 at 01:09
  • 1
    Why have two loops? You can keep the count as you go through. – Scary Wombat Jan 28 '19 at 01:09
  • I have reduced it to one loop. – SizableShrimp Jan 28 '19 at 01:11