首页 > 解决方案 > 如何限制用户回答?

问题描述

我正在创建一系列问题,我需要将用户输入限制为仅“A、B、C、D”,如果用户输入其他内容,则显示警告。我正在考虑创建一个if 条件来显示问题,但我不知道该怎么做。

这是我创建问题的方式:

     question= "Where Adolf Hitler was born?"
                + "\nA) USA"
                + "\nB) Austria"
                + "\nC) Germany"
                + "\nD) Spain";
     
     answer= JOptionPane.showInputDialog(question);
     
     if(answer=="D") {
         points++;
     }

标签: javaswingjoptionpane

解决方案


我认为人们忘记了诸如此类的JOptionPane可配置性。

从查看如何制作对话框开始了解更多详细信息

选上

import java.text.ParseException;
import javax.swing.JOptionPane;

public class Test {

    public static void main(String[] args) throws ParseException {
        String message = "Where Adolf Hitler was born?";
        String[] options = new String[] {
            "USA", "Austria", "Germany", "Spain"
        };
        int selectedOption = JOptionPane.showOptionDialog(null, message, "Pick one", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, 0);
        if (selectedOption == 1) {
            System.out.println("Right");
        } else {
            System.out.println("Wrong");
        }
    }
}

推荐阅读