Search code examples
javastringcompiler-errorsapplet

Error on the for loop - trying to use loop to count the repetition of letter


On the for loop I have the Java applet is showing me that I have an error. I am trying to use the for loop to count the repetition of letter.

String countString = "";
for (int i = 0; i < 26; i++){
// at the line below, my java applet says I have an error, and that the 
//"letterCounts" should be a int and not a string, but I need it to be a string
     String n = letterCounts[i];
     if (n.equals("0")) {
          countString = countString + "   ";
     } else if (n.length() == 1) {
          countString = countString + " " + n + " ";
     } else {
          countString = countString + n + " ";
     }
} 
this.countLabel.setText(countString);

Solution

  • You donot show the definition of letterCounts, but I bet it is int[] letterCounts.

    So since letterCounts is an array of int, you cannot just assign it to a String.

    Just change String n to int n and your comparison to n == 0 and it should work. See below:

        String countString = "";
    
        for (int i = 0; i < 26; i++)
        {
          int n = letterCounts[i];
    
          if (n == 0) {
            countString = countString + "   ";
          } else if (n < 10) {
            countString = countString + " " + n + " ";
          } else {
            countString = countString + n + " ";
          }
        } 
    
        this.countLabel.setText(countString);