Initializing a String with the information in the loop

  • A+
Category:Languages

I am receiving an error that the string may have not been initialized and I am thinking that i can not update my String using a for loop.

Moving the return statement inside the loop would not help and I do not want to introduce the String statement inside the for loop.

  public class HighScores    {       public static final int maxEntries = 10;       protected int numEntries;       protected Score[] entries;       public HighScores()       {         entries = new Score[maxEntries];         numEntries = 0;       }        public String toString(Score entries[])       {         // TODO                 String info;                 for(int i = 0; i < numEntries - 1; i++ )                 {                         System.out.println("(" + entries[i].getName() + ", "                          + entries[i].getScore() + ")");                          info = "(" + entries[i].getName() + ", " +                          entries[i].getScore() + ")";                 }                  return info; 

 


The compiler is correct. When your highscore is empty, the code inside the for loop is executed 0 times, which means than info was never assigned a value.

To fix this, start with an empty string:

String info = ""; 

Then, for each highscore entry, add its description to that string:

for (int i = 0; i < numEntries; i++) {     info += "("         + entries[i].getName() + ", "         + entries[i].getScore()         + ")"; } 

Note the info +=, which appends to the string, rather than replacing it.

Then, after all this hard work, return the info:

return info; 

Put together, the code looks like this:

public String toString() {      String info = "";      for (int i = 0; i < numEntries; i++) {         info += "("             + entries[i].getName() + ", "             + entries[i].getScore()             + ")";     }      return info; } 

Note that in the first line I wrote () instead of (Score[] entries) since the toString method usually takes no parameters.


If you are concerned about performance and large numbers (imagine a highscore having a million entries), the above code becomes terribly slow because the += string operator does a lot of unnecessary copying. Therefore, in an improved version of the code, you would use a StringBuilder instead. Plus you would use a list of highscore entries instead of an array. The code would then be:

private List<Score> highscore = new ArrayList<>();  public String toString() {     StringBuilder sb = new StringBuilder();     for (Score entry : entries) {         sb.append("(" + entry.getName() + " " + entry.getScore() + ")");     }     return sb.toString(); } 

This code reduces the copying a lot. It can be made even faster but that would make the code less readable:

public String toString() {     StringBuilder sb = new StringBuilder();     for (Score entry : entries) {         sb.append(')').append(entry.getName()).append(' ').append(entry.getScore()).append(')');     }     return sb.toString(); } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: