Huy
Huy

Reputation: 3

Treeset not adding all objects

I'm writing a dictionary for Vietnamese but my Treeset just add 1 object. I've been searching for 2 days but i cant figure it out how. hope you guys help me.

public class Word implements Comparable<Word> {

private static String word_target, word_explain;

public static void setWord_target(String word_target) {
    Word.word_target = word_target;
}

public static void setWord_explain(String word_explain) {
    Word.word_explain = word_explain;
}

public String getWord_explain() {
    return word_explain;
}

public String getWord_target() {
    return word_target;
}

@Override
public int compareTo(Word word) {
    return this.getWord_target().compareTo(word.getWord_target());
}
}

public class Dictionary {

private TreeSet<Word> words = new TreeSet<Word>();

public TreeSet<Word> getWords() {

    return words;
}
}

public class DictionaryManagement {

static Scanner reader = new Scanner(System.in);

public static int numbers;

public static void insertFromCommandline(Dictionary dic) {

    numbers = reader.nextInt();

    reader.nextLine();
    for (int i = 0; i < numbers; i++) {

        Word putInWord = new Word();

        String en_word, vn_word;

        System.out.print("English Word: ");
        en_word = reader.nextLine();
        putInWord.setWord_target(en_word);



        System.out.print("VietNameses Word: ");
        vn_word = reader.nextLine();
        putInWord.setWord_explain(vn_word);


        dic.getWords().add(putInWord);

    }

}
}

public class DictionaryCommandline {

private static int num = 1;
public static Dictionary showWord = new Dictionary();

public static void showAllWords() {
    System.out.println("No      |English            |Vietnamese");

    for (Word wr : showWord.getWords()) {

        System.out.println( num++ + "       |" + wr.getWord_target() + "             |" +  wr.getWord_explain());
    }

}

public static void dictionaryBasic() {
    DictionaryManagement.insertFromCommandline(showWord);
    DictionaryCommandline.showAllWords();
}

}

public class Main {

public static void main(String []args) throws Exception {

    DictionaryCommandline.dictionaryBasic();

}
}

Example:

Input:

2

English Word:

house

VietNameses Word:

ngoi nha

English Word:

name

VietNameses Word:

ten

-Actual Output:

No English Vietnam

1 name ten

-Expected Output:

No English Vietnam

1 house ngoi nha

2 name ten

Upvotes: 0

Views: 52

Answers (1)

Diogo Silv&#233;rio
Diogo Silv&#233;rio

Reputation: 344

@Huy, note that you are using static variables, try using only instance variables for your Word, instances.

This makes your compareTo method always compare the latest words you inserted because static variables are associated only with a class, representing a single value/instance at a time.

Take a look here for a few more words on static @ java

Upvotes: 2

Related Questions