JOptionPane and reading integers - Beginner Java

﹥>﹥吖頭↗ 提交于 2019-11-27 04:52:54

问题


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(System.in);
int day = 0;
int month = 0;
int year = 0;

System.out.printf("enter the month, date, and year(a 2 numbered year). Put a space between the month, day, and year");
month = input.nextInt();
day = input.nextInt();
year = input.nextInt();

This works fine, the second part is to display a message, if month * day == year, then it is a magical number, if not, then it is not a magical number. It has to be displayed in a dialog box. here is my code for that, and it is working just fine.

  if((day * month) == year)
  {
    String message = String.format("%s", "The date you entered is MAGIC!");//If the day * month equals the year, then it is a magic number
    JOptionPane.showMessageDialog(null, message);
  }
  if((day * month) != year)
  {  
    String message = String.format("%s", "The date you entered is NOT MAGIC!");//If the day * month does not equal the year, it is not a magic number
    JOptionPane.showMessageDialog(null, message);
  }

My question is!! How can I get a dialog box to take the inputs of the month, date, and year in one line the way it works in the console. I'm working in DrJava, and the chapter of the book I'm in doesn't help me with this specific use. Any help would be great. Thanks all!


回答1:


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




回答2:


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.

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

Or JComboBox

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




回答3:


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.



来源:https://stackoverflow.com/questions/14783836/joptionpane-and-reading-integers-beginner-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!