我正在为越南语写字典,但是我的树集只添加了一个对象。我一直在寻找2天,但我不知道怎么办。希望你们能帮助我。
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();
}
}
示例:
输入:
2
英语单词:
房子
越南语单词:
ngoi nha
英语单词:
名称
越南语单词:
十
-实际输出:
没有英语越南语
1个名字十个
-预期输出:
没有英语越南语
一所房子ngoi nha
2个名字十个
答案 0 :(得分:2)
@Huy,请注意,您正在使用静态变量,请尝试仅对Word实例使用实例变量。
这使您的compareTo方法总是比较插入的最新单词,因为静态变量仅与一个类关联,一次代表一个值/实例。
看看here,了解有关静态@ java的更多信息