【问题标题】:Enum of enums [JAVA]枚举的枚举 [JAVA]
【发布时间】:2014-03-25 19:05:06
【问题描述】:

好的,所以我编写了一个 Java 程序来测试我的冷战历史日期,我想用一个简单的框架来扩展它以涵盖所有主题。我正在考虑用不同的主题(它们本身就是枚举)制作一个枚举。我知道我可以制作一个带有 JOptionPane 的 GUI 来选择或其他东西,但我想让它尽可能动态(因为不必对选项进行硬编码)。到目前为止,这是我所拥有的:

public class Main {
    public List<History> list = new ArrayList<>();
    public List<History> generated = new ArrayList<>();
    private final Random r = new Random();
    private final MainFrame frame = new MainFrame(nextQuestion(), Main.this);
    private int correctInFirstGo = History.values().length;

    public static void main(String[] args) {
        new Main();
    }
    public Main() {
        SwingUtilities.invokeLater(() ->frame.setVisible(true));
    }

    public void setCorrect(boolean b, int attempts) {
        if (list.size() == History.values().length) {
            JOptionPane.showMessageDialog(frame, "You got " + correctInFirstGo + "/" + History.values().length);
            frame.dispose();
            System.out.println(list);
            System.out.println(generated);
            return;
        }
        loop:
        if (b) {
            final History h = nextQuestion();
            if (generated.contains(h) && !list.contains(h)) {
                System.out.println(h);
                frame.setQuestion(h);
            } else {
                break loop;
            }
        } else if (attempts != 1) {
            correctInFirstGo--;
        }
    }

    private History nextQuestion() {
        History[] values = History.values();
        History h = values[r.nextInt(values.length)];
        if (list.contains(h)) {
            return nextQuestion();
        }
        generated.add(h);
        return h;
    }
}


public class MainFrame extends JFrame{

    private Main m;
    private History h;
    private JLabel questionLabel;
    private JLabel verdictLabel;
    private JTextField answerField;
    private JButton checkButton;
    private JLabel questionNumber;
    private JLabel attemptLabel;
    private int attempt = 1;

    public MainFrame(History h, Main m) {
        System.out.println(h);
        this.h = h;
        this.m = m;
        initComponents();
    }

    private void initComponents() {
        questionLabel = new JLabel("", SwingConstants.CENTER);
        answerField = new JTextField();
        checkButton = new JButton();
        verdictLabel = new JLabel("", SwingConstants.CENTER);
        questionNumber = new JLabel("");
        attemptLabel = new JLabel("" + attempt);

        setTitle("History Test");
        Container contentPane = getContentPane();
        contentPane.setLayout(null);

        setQuestion(h);
        checkButton.setText("Check");
        verdictLabel.setText("");

        questionLabel.setBounds(5, 5, 345, 25);
        answerField.setBounds(148, 35, 55, 25);
        checkButton.setBounds(138, 65, 75, 25);
        verdictLabel.setBounds(5, 90, 345, 25);
        questionNumber.setBounds(5, 90, 50, 25);
        attemptLabel.setBounds(320, 90, 15, 25);

        answerField.addActionListener(ae -> checkSolution());
        checkButton.addActionListener(ae -> checkSolution());

        contentPane.add(questionLabel);
        contentPane.add(answerField);
        contentPane.add(checkButton);
        contentPane.add(verdictLabel);
        contentPane.add(questionNumber);
        contentPane.add(attemptLabel);

        setResizable(false);
        setLocationRelativeTo(null);
        pack();
        setSize(350, 140);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void setQuestion(History h) {
        this.h = h;
        String question = "What year was the " + h + "?";
        questionLabel.setText(question);
        answerField.setText("");
        m.list.add(h);
        questionNumber.setText("" + m.generated.size() + "/" + History.values().length);
    }

    private void checkSolution() {
        answerField.requestFocus();
        if (answerField.getText().equals(h.answer())) {
            verdictLabel.setText("Correct!");
            m.setCorrect(true, attempt);
            attemptLabel.setText((attempt = 1) + "");
        } else {
            verdictLabel.setText("Try again!");
            m.setCorrect(false, attempt);
            attempt++;
            attemptLabel.setText(attempt + "");
        }
    }
}

public enum History{
    // my constants here

    private String answer;
    private String toString;
    private final String[] ignoreCapitals = {"of", "the", "built"};

    History(String answer) {
        this.answer = answer;
    }

    public String answer() {
        return answer;
    }

    @Override
    public String toString() {
        if (toString != null) { return toString; }
        final String name = name();
        final String[] words = name.replace('$', '\'').split("_+");
        final StringBuilder result = new StringBuilder(name.length());
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            final String newWord = performCapitalization(word, i);
                if (newWord != null) {
                result.append(newWord);
            }
            if(i < words.length - 1){
                result.append(' ');
            }
        }

        return (toString = result.toString());
    }

    private String performCapitalization(final String oldWord, final int index) {
        if(oldWord == null || oldWord.length() == 0){
            return null;
        }
        boolean ignore = false;
        if (index != 0) {
            for (final String str : ignoreCapitals) {
                if(str.equalsIgnoreCase(oldWord)){
                    ignore = true;
                    break;
                }
            }
        }
        final String newWord = oldWord.toLowerCase();
        if(ignore){
            return oldWord.toLowerCase();
        }
        return Character.toUpperCase(newWord.charAt(0)) + newWord.substring(1);
    }
}

任何帮助将不胜感激。

【问题讨论】:

  • 您在寻找什么样的答案?我不确定你在问什么
  • 这里有很多代码要经过。您对特定作品有疑问吗?
  • 枚举的枚举?对我来说听起来有点奇怪,可序列化的list&lt;?&gt; 怎么样?
  • @user3334690 我正在寻求一些帮助,了解如何使其更具动态性,以便我可以在不同的问题和答案之间进行选择,例如,无需硬编码案例即可轻松地进行选择。 JustinJasmann 就是上面提到的。 parsaporahmad 我还没有使用可序列化,那是什么?

标签: java list generics enums enumeration


【解决方案1】:

首先,我会考虑将问题存储在一个文件中(xml/json 似乎是自然的选择)。

如果您想要一种在代码中创建问题的好方法,为什么不创建一个带有 fluent api 的库呢?因此,您正在查看以下内容:

QuestionSet = new QuestionSet("QS1")
                   .addTopic( new Topic("topic 1")
                                  .addQuestion( new Question("text"...)
                                  .addQuestion( new Question("text"...) )
                   .addTopic( new Topic("topic 2")
                                  .addQuestion( new Question("text"...) )

【讨论】:

  • 这将是一个可行的选择,如果我想不出别的,我会考虑一下。
【解决方案2】:

使用 Hashmap 的 Hashmap 会更好。这将为您提供所需的灵活性。

【讨论】:

  • 你是对的@Injustice,这正是它的工作原理,而使用这样的地图(或字典)地图的美妙之处在于它类似于 Json 结构并且可以轻松转换为一。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-10
  • 1970-01-01
  • 1970-01-01
  • 2011-07-09
  • 2011-03-22
  • 2015-08-08
相关资源
最近更新 更多