【问题标题】:Java Program StructureJava 程序结构
【发布时间】:2021-12-17 13:56:57
【问题描述】:

我正在构建一个应用程序,根据用户从下拉菜单中的选择来打印不同语言的单词。但是,我当前的方法有效,因为我从嵌套类中获取数据并从完全不同的类中请求它,这需要为嵌套类中的每个单词编写一行代码。我怎样才能以更有效/更轻松的方式实现这一目标?以下是上述代码的基本格式:

public class words {

   class example {
       String english = "example";
       String chinese = "example_in_chinese";
   }

   class example2 {
       String english = "example2";
       String chinese = "example2_in_chinese";
   }
}


public class getWords {

    words word = new words();
    words.example example = word.new example();
    words.example2 example2 = word.new example2();

    */ I have to repeat the above line for each of the 20 
    words I have in a nested class
    /*

}

【问题讨论】:

  • 也许使用字典。在 Java 中实现字典的一种方法是使用 java.util.Map 来保存一个英文单词作为键和一个中文单词作为值。

标签: java inner-classes


【解决方案1】:

我想你可以尝试使用地图。

public class Words {
    static Map<String, String> example1 = new HashMap<String, String>();
    example1.put("english", "example");
    example1.put("chinese", "example_in_chinese");

    static Map<String, String> example2 = new HashMap<String, String>();
    example2.put("english", "example2");
    example2.put("chinese", "example2_in_chinese");
}

所以你可以打电话

Words.example1.get("english");

或者更进一步,你可以创建一个枚举语言

enum Language {
    ENGLISH, CHINESE
}

public class Words {
    static Map<Language, String> example1 = new HashMap<Language, String>();
    example1.put(Language.ENGLISH, "example");
    example1.put(Language.CHINESE, "example_in_chinese");

    static Map<Language, String> example2 = new HashMap<Language, String>();
    example1.put(Language.ENGLISH, "example2");
    example1.put(Language.CHINESE, "example2_in_chinese");
}

Words.example1.get(Language.ENGLISH);

只是为了减少打字错误的可能性。

【讨论】:

  • 感谢您的回答。我现在陷入另一个问题。我有一个从字符串数组填充的 JComboBox,但是我需要将这些项目与 HashMap 中的项目相关联,以便我可以调用和打印给定单词的所有语言。示例:: 如果用户选择 example1 打印 example1.get("english");打印 example1.get("中文");等等......每种语言
  • 我认为您需要将其作为一个新问题发布。
【解决方案2】:

也许您可以使用责任链设计模式来确定适合打印的语言。

用代码显示需要很长时间,但我会给你提示。

遍历对象以查找具有给定下拉值的可打印语言。 如果找不到合适的打印语言,请忽略它。

https://www.tutorialspoint.com/design_pattern/chain_of_responsibility_pattern.htm

【讨论】:

  • 听起来 OP 是 Java 的新手,谈论设计模式可能会让他/她更加困惑。
猜你喜欢
  • 2011-03-10
  • 1970-01-01
  • 1970-01-01
  • 2012-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-23
  • 2019-03-09
相关资源
最近更新 更多