【问题标题】:How will the condition work in JOptionPane?条件将如何在 JOptionPane 中发挥作用?
【发布时间】:2016-02-28 09:45:52
【问题描述】:

我正在尝试制作两个类别的测验程序:Java 或 C++。我想做一个有4个答案的问题(多选),但我不知道条件会如何工作以及用户分数将如何保存。

应用程序使用JOptionPanes 与用户交互。

这是我目前所拥有的:

import javax.swing.JOptionPane;

public class Quiz1
{
    public static void main(String[] args) 
    {
        int score = 0;
        JOptionPane.showMessageDialog(null,"WELCOME");
        String name = JOptionPane.showInputDialog(null,"Enter Your Name: ");

        String [] Intro = new String [] {"JAVA","C++"};
        int option = JOptionPane.showOptionDialog(null, "Choose a Category" , "Menu", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,  Intro, Intro[0]);


        if (option == JOptionPane.YES_OPTION) // I just make YES or NO option since there are 2 choices
        {
            JOptionPane.showMessageDialog(null, "Hello "+ name + "\n Welcome to Java Quiz!");
            JOptionPane.showMessageDialog(null, "1. Please read the questions carefully \n 2. Answer all the question \n 3. Scores will be computed after the quiz \n 4. No Cheating!","RULES",JOptionPane.WARNING_MESSAGE);
            JOptionPane.showMessageDialog(null, "This Quiz consist of \n 1. Multiple Choice \n 2.Enumeration \n 3. True/False");
            JOptionPane.showMessageDialog(null,"Quiz #1: Enter the correct letter of the answer");

            // STRING OF QUESTIONS
            String[] quesJava = new String [] {"1) The JDK command to compile a class in the file Test.java is", "2)    Java was developed by_____."};


            String[] answers1 = new String[] {"A) java Test.java", "B) java Test","C) javac Test","D) javac Test.java"};
            int answer1 = JOptionPane.showOptionDialog(null, quesJava[0], "JAVA", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, answer1, answer1[0]);

            if (answer1== ???????????) // the answer is letter "D" but I don't know what will I put in here
            {
                score++;
            }

            String[] answer2 = new String[] {"A) IBM ", "B) Microsoft ","C) Sun Microsystem ","D) Oracle"};
            int answer2 = JOptionPane.showOptionDialog(null, quesJava[1], "JAVA", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, answer2, answer2[0]);
            {
                if (answer2== )
                {
                    score++;
                }
            }
            JOptionPane.showMessageDialog(null,"your score is"+score);
        }
    }
}

【问题讨论】:

    标签: java arrays if-statement joptionpane


    【解决方案1】:

    我将重写您提供的代码以使这更容易...

    这是最终结果:

    import java.util.Random;
    import javax.swing.JOptionPane;
    
    public class Quiz {
    
        /**
         * This holds all the java questions.
         */
        private static final Question[] JAVA_QUESTIONS = new Question[]{
            new Question("Who developed Java?", 2, "Google", "Sun Microsystems", "Microsoft", "Oracle"),
            //This creates the question: Who developed java with 4 answers (google, Sun, Microsoft and Oracle)
            //The correct answer is 2 (Sun).
            new Question("What modifier is used to make a variable constant?", 3, "public", "abstract", "final", "import")
        };
    
        /**
         * This holds all the c++ questions.
         */
        private static final Question[] CPP_QUESTIONS = new Question[]{
            new Question("C++ is?", 4, "Interpreted", "A scripting language", "The first programming language", "Compiled")
        };
    
        /**
         * The users score
         */
        private int score;
    
        /**
         * The users name
         */
        private String name;
    
        /**
         * What language the user selected.
         */
        private Language lang;
    
        private Quiz() {
            setLookAndFeel();//Makes everything look nice
            showOpeningDialogs();//Shows the welcome dialogs
            askQuestions(10);//Asks random questions 10 times depending on what language is selected. 
        }
    
        /**
         * Asks random questions depending on the language chosen.
         *
         * @param maxScore the number of questions to ask
         */
        private void askQuestions(int maxScore) {
            for (int i = 0; i < maxScore; i++) {
                Question q = getRandomQuestion(lang);//Gets a random question for the language chosen.
                if (ask(q)) {//Checks if they got it correct
                    JOptionPane.showMessageDialog(null, "You answered correctly");//Tell them they got it correct
                    score++;//Increment their score.
                } else {//If they got it wrong
                    JOptionPane.showMessageDialog(null, "You answered incorrectly. The answer is: " + q.getChoices()[q.getCorrectAnswer()]);
                    //Tell them they got it wrong and what the correct answer is.
                }
            }
    
            JOptionPane.showMessageDialog(null, "Your score is: " + score + "/" + maxScore);//At the end, tell them their score
        }
    
        /**
         * Asks a question and returns whether the player got it correct.
         *
         * @param question
         * @return
         */
        private boolean ask(Question question) {
            //Shows a dialog with the question and answers.
            int choice = JOptionPane.showOptionDialog(
                    null,
                    question.getQuestion(),
                    lang.getDisplayName(),
                    JOptionPane.DEFAULT_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    question.getChoices(),
                    question.getChoices()[0]);
    
            //Checks to see if the answer is correct. This is determined by the answer variable in the question object.
            if (choice == question.getCorrectAnswer()) {
                return true;
            }
    
            return false;
        }
    
        /**
         * Just makes everything look nice. You don't have to worry about this.
         */
        private void setLookAndFeel() {
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if (/**What java look and feel*/
                            "Windows".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
                //Very unlikely to happen
            }
        }
    
        /**
         * Shows the welcome dialogs and so on.
         */
        private void showOpeningDialogs() {
            name = JOptionPane.showInputDialog(null, "Welcome.\nPlease enter you name:");//Gets the users name.
    
            String[] langs = new String[]{Language.JAVA.getDisplayName(), Language.CPP.getDisplayName()};
            int opt = JOptionPane.showOptionDialog(null, "Please chose your language", "Menu", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, langs, langs[0]);//Gets the language the user chose.
    
            //Set the language depending on the users choice.
            switch (opt) {
                case JOptionPane.YES_OPTION:
                    lang = Language.JAVA;
                    break;
                default:
                    lang = Language.CPP;
            }
    
            //The instructions.
            JOptionPane.showMessageDialog(null, "Hello " + name + "\nWelcome to the " + lang.getDisplayName() + " Quiz!");
            JOptionPane.showMessageDialog(null, "1. Please read the questions carefully \n2. Answer all the question \n3. Scores will be computed after the quiz \n4. No Cheating!", "RULES", JOptionPane.WARNING_MESSAGE);
            JOptionPane.showMessageDialog(null, "This Quiz consist of \n 1. Multiple Choice");
    
            //Do they want to continue
            int begin = JOptionPane.showOptionDialog(null, "Are you ready to begin?", "Menu", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, new String[]{"Yes", "No"}, "Yes");
    
            if (begin != JOptionPane.YES_OPTION) {
                System.exit(0);
            }
        }
    
        /**
         * Gets a random question for a language
         *
         * @param lang the language
         * @return a random question
         */
        private Question getRandomQuestion(Language lang) {
            switch (lang) {
                case JAVA://If the language is java, choose a java question.
                    int random = new Random().nextInt(JAVA_QUESTIONS.length);
                    return JAVA_QUESTIONS[random];
                case CPP://Else choose a C++ question.
                    random = new Random().nextInt(CPP_QUESTIONS.length);
                    return CPP_QUESTIONS[random];
            }
    
            return null;
        }
    
        public static void main(String[] args) {
            Quiz q = new Quiz();//Just starts the application.
        }
    
        /**
         * This class holds a question, the correct answer and the choices.
         */
        private static final class Question {
    
            /**
             * The question being asked
             */
            private final String question;
    
            /**
             * The correct choice. The index of the choices array.
             */
            private final int correctAnswer;
    
            /**
             * The 4 choices the player can choose
             */
            private final String[] choices;
    
            public Question(String question, int correctAnswer, String... choices) {
                if (question == null) {
                    throw new NullPointerException("The question cannot be null");
                }
    
                if (correctAnswer < 1 || correctAnswer > 4) {
                    throw new IllegalArgumentException("Correct answer must be between 0 and 5 (1 to 4)");
                }
    
                if (choices == null) {
                    throw new NullPointerException("choices cannot be null");
                }
    
                if (choices.length != 4) {
                    throw new NullPointerException("Choices must have 4 options");
                }
    
                this.question = question;
                this.correctAnswer = correctAnswer - 1;
                this.choices = choices;
            }
    
            /**
             * @return the question
             */
            public String getQuestion() {
                return question;
            }
    
            /**
             * @return the correctAnswer
             */
            public int getCorrectAnswer() {
                return correctAnswer;
            }
    
            /**
             * @return the choices
             */
            public String[] getChoices() {
                return choices;
            }
        }
    
        /**
         * Which language we're using
         */
        private enum Language {
    
            /**
             * The Java programming language
             */
            JAVA("Java"),
            /**
             * The C++ programming language
             */
            CPP("C++");
    
            //The display name for the language
            private final String displayName;
    
            Language(String displayName) {
                this.displayName = displayName;
            }
    
            public String getDisplayName() {
                return displayName;
            }
        }
    }
    

    它的作用: 根据所选语言随机提问。

    它是如何做到的:

    首先询问用户:他们的姓名和他们想要被测试的语言。这是在showOpeningDialogs() 方法中完成的。他们在变量namelang 中提供的信息。

    然后继续提问(重要部分)

    在类的最顶端,我们有两个存放问题的数组,一个用于 Java(JAVA_QUESTIONS),另一个用于 C++(CPP_QUESTIONS)。这些数组包含问题、答案和正确答案。要添加更多问题,您只需向数组中添加一个新问题即可。

    方法askQuestions(int maxScore) 被调用。它首先从方法getRandomQuestion(Language lang) 获取一个随机问题,然后调用方法ask(Question question) 向用户显示问题并返回他们是否正确。如果他们做对了,score 变量就会增加,并且一个对话框告诉他们他们做对了,如果他们做错了,一个对话框会出现,告诉他们正确的答案。这会循环您使用变量maxScore 指定的次数(这可能低于数组中的问题数)

    代码记录得很好,可以指导您了解正在发生的事情。

    您将不得不对代码进行一些操作才能完全理解它,但在大多数情况下,您想要的内容相当简单。

    【讨论】:

    • 这很好,但有些方法对我来说是新的。我刚开始学习java。我目前正在学习 java 1 (basic),你提供的指导方针真的很有帮助。谢谢
    【解决方案2】:

    如果您查看documentation of JOptionPane,您可能已经看到了:

    public Object[] getSelectionValues():

    返回输入选择值。

    还有public Object getValue():

    返回用户选择的值。 UNINITIALIZED_VALUE 表示用户尚未做出选择,null 表示用户没有选择任何内容就关闭了窗口。否则返回值将是此对象中定义的选项之一。

    这让您的问题很容易解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2017-10-20
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      相关资源
      最近更新 更多