JOptionPane and reading integers - Beginner Java

前端 未结 3 1518
深忆病人
深忆病人 2020-12-07 05:10

I currently have code that reads the month, date, and year a user enters in one line (separated by spaces). Here is the code.

Scanner input = new Scanner(Sys         


        
相关标签:
3条回答
  • 2020-12-07 05:32

    Here's some code, everything is described in the comments:

    // import statements
    import javax.swing.JOptionPane;
    // main class
    public class Main {
        // main method
        public static void main(String[] args) {
            // get info
            try {
                Info info = new Info();
            } catch(Exception e) {
                System.err.println("Error! " + e.getMessage());
            }
            // do whatever with the info
        }
        // info class
        static class Info {
            // instance variables
            public int day, month, year;
            // constructor
            public Info() throws Exception {
                // get inputs
                String[] inputs = JOptionPane.showInputDialog(null, 
                    "Enter day, month, year").split(" ");
                // not the right size
                if(inputs.length != 3) {   
                    throw new Exception("Not enough infomation was given!");
                }
                // get values
                day = Integer.parseInt(inputs[0]);
                month = Integer.parseInt(inputs[1]);
                year = Integer.parseInt(inputs[2]);
            }
        }
    }
    

    It has an elegant way of notifying you if something went wrong, and everything you need is packaged up in a convenient object.

    0 讨论(0)
  • 2020-12-07 05:35

    You can make use of following to take user input

    String word = JOptionPane.showInputDialog("Enter 3 int values");
    String[] vals = word.split("\\s+"); // split the sting by whitespaces accepts regex. 
    // vals[0] cast to int
    // convert string representation of number into actual int value
    int day = Integer.parseInt(vals[0]); // throws NumberFormatException
    // vals[1] cast to int
    // vals[2] cast to int
    

    split Java API

    parseInt Java API

    Java Regex Tutorial

    0 讨论(0)
  • 2020-12-07 05:41

    There are a number of ways to approach the problem depending on ultimately what it is you want to achieve.

    JOptionPane allows you to supply Object as the message. If this message is a String it will rendered as is, however, if it is a Component of some kind, it will be simply added to the dialog. This makes JOptionPane a very powerful little API.

    enter image description here

    public class TestOptionPane07 {
    
        public static void main(String[] args) {
            new TestOptionPane07();
        }
    
        public TestOptionPane07() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    JTextField fldDay = new JTextField(3);
                    JTextField fldMonth = new JTextField(3);
                    JTextField fldYear = new JTextField(4);
                    JPanel message = new JPanel();
                    message.add(fldDay);
                    message.add(new JLabel("/"));
                    message.add(fldMonth);
                    message.add(new JLabel("/"));
                    message.add(fldYear);
    
                    int result = JOptionPane.showConfirmDialog(null, message, "Enter Date", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                    if (result == JOptionPane.OK_OPTION) {
                        String sDay = fldDay.getText();
                        String sMonth = fldMonth.getText();
                        String sYear = fldYear.getText();
                        JOptionPane.showMessageDialog(null, "You enetered " + sDay + "/" + sMonth + "/" + sYear);
    
                        try {
                            int day = Integer.parseInt(sDay);
                            int month = Integer.parseInt(sMonth);
                            int year = Integer.parseInt(sYear);
                            JOptionPane.showMessageDialog(null, "You enetered " + day + "/" + month + "/" + year);
                        } catch (Exception e) {
                            JOptionPane.showMessageDialog(null, "The values you entered are invalid");
                        }
                    }
                }
            });
        }
    }
    

    Updated

    If I was going to use something like this, I would also use a DocumentFilter to ensure that the user could only enter valid values (examples here)

    But you could also use JSpinners

    enter image description hereenter image description here

    Or JComboBox

    enter image description here

    Depending on what it is you want to achieve...

    0 讨论(0)
提交回复
热议问题