Search code examples
javaconstructorcomparable

Writing a constructor for a Letter counter


I need to write this constructor for a client code that will read in a text file and count the number of instances of each letter of the alphabet. When the constructor is run in the client code, it will output the letter and then the number of instances it occurred in the file, example: "a" occurred 65 times. I'm having trouble overwriting the toString method as I get ';' expected as a compiler error every time I try and I've tried several methods I've found on the web. Also, I have no idea what I'm doing with the toCompare method. I've looked around the internet and nothing works quite right. Below are the exact instructions for the assignment and what I have so far. Any help would be greatly appreciated, as always.

create a class LetterCount that:

1) stores a single character (a letter) and a count (an integer) in private variables

2) implements the Comparable interface, thus there must be a compareTo() method which should compare two LetterCount objects by their count values

3) overrides toString() with a printable representation that shows the letter and the count

public class LetterCount implements Comparable<LetterCount> {
        private String letter;
        private int count;

        public LetterCount(String l, int x) {
            letter = l;
            count = x;
        }

        public String toString() {
            return "Letter" + letter + " occurs "+ count " + times";
        }
         public int compareTo(LetterCount other) {




    }
    }

Solution

  •     return "Letter" + letter + " occurs " + count + " times";
    

    Missing a + and the variable names are wrong.

    public int compareTo(LetterCount other) {
        if ( count < other.count )
           return -1;
        else if (count == other.count)
           return 0;
        else
           return 1;
    }