当前位置: 首页 > 知识库问答 >
问题:

我怎样才能提示Java的用户输入一周中的某一天,枚举中的天数输出我想要的响应

柴赞
2023-03-14

我正在学习Java,我遇到了一个问题,我需要在枚举中输入一周中的几天。然后,我需要将几个响应放入switch case语句中,并让用户在JOptionPane中输入星期几,然后让程序输出适当的响应。

这是我的枚举:

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,THURSDAY, FRIDAY, SATURDAY; 
}

这是我试图得到正确的回应:

public class enumDayMood {
    Day day;
    
    public static void main(String[] args){
        String day = JOptionPane.showInputDialog("Enter the day of the week.");
    }
    
    public void telDayMood(){
        
        Day day = Day.MONDAY;
        
        switch(day){
            case MONDAY:
                JOptionPane.showMessageDialog(null,"Mondays are bad.");
                break;
            case FRIDAY:
                JOptionPane.showMessageDialog(null,"Fridays are better.");
                break;
            case SATURDAY: case SUNDAY:
                JOptionPane.showMessageDialog(null,"Weekends are best");
                break;
            default:
                JOptionPane.showMessageDialog(null,"Midweek days are so-so.");
                break;
        }
    }
    
}

我能够在一周中的每一天单独输出,但我似乎不能让用户输入工作。我试过多种方法,但似乎都不奏效。

共有1个答案

裴令秋
2023-03-14

我建议使用showOptionDialog方法,而不是showInputDialog/code>。让一周中的每一天都成为一种选择。然后用户只需要点击相关的按钮,这样就可以节省一些工作,不是吗?请考虑以下内容:

import javax.swing.JOptionPane;

public class WeekDays {
    public enum Day {
        SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
    }

    public static void main(String[] args) {
        int index = JOptionPane.showOptionDialog(null,
                                                 "Enter the day of the week.",
                                                 "Moody",
                                                 JOptionPane.DEFAULT_OPTION,
                                                 JOptionPane.QUESTION_MESSAGE,
                                                 null,
                                                 Day.values(),
                                                 Day.MONDAY);
        Day selection = Day.values()[index];
        switch (selection) {
            case MONDAY:
                JOptionPane.showMessageDialog(null,"Mondays are bad.");
                break;
            case FRIDAY:
                JOptionPane.showMessageDialog(null,"Fridays are better.");
                break;
            case SATURDAY: case SUNDAY:
                JOptionPane.showMessageDialog(null,"Weekends are best");
                break;
            default:
                JOptionPane.showMessageDialog(null,"Midweek days are so-so.");
                break;
        }
        System.exit(0);
    }
}

这就是我运行它时的样子。

 类似资料: