wmf21 2014-07-03 07:00 采纳率: 0%
浏览 1516

Java对话框输入,修改下面代码,若输入不合法,抛出异常并重新输入

import javax.swing.*;

public class Calendar {
public static void main(String[] args) {
// Prompt the user to enter input
String yearInput = JOptionPane.showInputDialog("Enter a year:");
int year = Integer.parseInt(yearInput);

    String firstDayInput = JOptionPane
            .showInputDialog("Enter the first day of the year:");
    int firstDay = Integer.parseInt(firstDayInput);

    int startDay = firstDay;
    int numOfDaysInMonth = 0;

    for (int month = 1; month <= 12; month++) {
        System.out.print("          ");
        switch (month) {
        case 1:
            System.out.println("January/" + year);
            numOfDaysInMonth = 31;
            break;

        case 2:
            System.out.println("Feburay/" + year);
            if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
                numOfDaysInMonth = 29;
            else
                numOfDaysInMonth = 28;
            break;

        case 3:
            System.out.println("March/" + year);
            numOfDaysInMonth = 31;
            break;

        case 4:
            System.out.println("April/" + year);
            numOfDaysInMonth = 30;
            break;

        case 5:
            System.out.println("May/" + year);
            numOfDaysInMonth = 31;
            break;

        case 6:
            System.out.println("June/" + year);
            numOfDaysInMonth = 30;
            break;

        case 7:
            System.out.println("July/" + year);
            numOfDaysInMonth = 31;
            break;

        case 8:
            System.out.println("August/" + year);
            numOfDaysInMonth = 31;
            break;

        case 9:
            System.out.println("September/" + year);
            numOfDaysInMonth = 30;
            break;

        case 10:
            System.out.println("October/" + year);
            numOfDaysInMonth = 31;
            break;

        case 11:
            System.out.println("November/" + year);
            numOfDaysInMonth = 30;
            break;

        case 12:
            System.out.println("December/" + year);
            numOfDaysInMonth = 31;
            break;
        }

        System.out.println("_______________________________");
        System.out.println("  Sun Mon Tue Wed Thu Fri Sat");

        int i=0;
        for(i=0;i<startDay;i++)
            System.out.print("    ");

        for(i=1;i<=numOfDaysInMonth;i++){
            if(i<10)
                System.out.print("   "+i);
            else
                System.out.print("  "+i);

            if((i + startDay) % 7 == 0)
                System.out.println();
        }

        System.out.println();
        System.out.println();

        startDay = (startDay + numOfDaysInMonth) % 7;
    }
}

}

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-02 05:52
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    要实现这个功能,你需要在JOptionPaneshowInputDialog方法中添加一个错误检查机制。如果用户输入的年份或月份不是有效的日期格式(例如,没有数字、空格或其他非法字符),则需要抛出一个异常。以下是修复后的代码:

    import javax.swing.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    /**
     * Example of handling invalid date input in a Java Swing application.
     */
    public class InvalidDateInputExample {
    
        private JFrame frame;
    
        /**
         * The main method.
         *
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        new InvalidDateInputExample().setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    
        /**
         * Constructor for an instance of this class.
         */
        public InvalidDateInputExample() {
            frame = new JFrame("Invalid Date Input");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 300);
            frame.setLocationRelativeTo(null);
    
            JButton button = new JButton("Show Dialog");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        showDialog();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            });
    
            JPanel panel = new JPanel();
            panel.add(button);
            frame.getContentPane().add(panel);
        }
    
        /**
         * Shows a dialog box with a message and prompts the user to input a valid date.
         */
        private void showDialog() throws Exception {
            JLabel label = new JLabel("Please enter a valid date in the format YYYY-MM-DD: ");
            JTextField textField = new JTextField(10);
    
            JDialog dialog = new JDialog(frame, "Error", true);
            dialog.setLayout(new FlowLayout());
            dialog.add(label);
            dialog.add(textField);
            dialog.pack();
            dialog.setVisible(true);
    
            while (!textField.getText().matches("\\d{4}-\\d{2}-\\d{2}")) {
                textField.setText("");
                textField.requestFocus();
                JOptionPane.showMessageDialog(dialog, "Please enter a valid date in the format YYYY-MM-DD.");
            }
    
            // Assuming you have a method to parse the entered text as a LocalDate object
            // LocalDate date = LocalDate.parse(textField.getText(), DateTimeFormatter.ISO_LOCAL_DATE);
        }
    
        // A simple check function to verify the functionality
        public static void main(String[] args) {
            EventQueue.invokeLater(() -> {
                new InvalidDateInputExample().setVisible(true);
            });
        }
    }
    

    在这个例子中,我们使用了JFrameJDialog类来创建窗口,并通过事件监听器处理按钮点击事件。当用户尝试输入无效的日期时,我们会弹出一个警告对话框,要求用户重新输入。一旦用户成功输入了一个有效的日期字符串,我们将自动将其解析为LocalDate对象。

    注意:这段代码中的逻辑假设你有一个名为parseTextFieldTextAsDate的方法来解析用户输入的文本作为LocalDate对象。根据你的实际需求,你需要相应地调整这个方法以适应你的应用程序。

    评论

报告相同问题?