1

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!

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
ShiftyMcGrifty
  • 25
  • 1
  • 1
  • 6

3 Answers3

6

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...

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • I appreciate the help greatly! While this is my 4th week in a programming class, I don't think this is what my professor is expecting of us just yet. I'm not familiar with writing my own methods or programs that use more than one class. But I do understand now the complexity and usefulness that the JOptionPane offers. – ShiftyMcGrifty Feb 09 '13 at 02:39
  • Yeah, I think a lot of people fail to recognise just how powerful something like JOptionPane can really be. Find the best solution for your needs! – MadProgrammer Feb 09 '13 at 03:29
2

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

Smit
  • 4,685
  • 1
  • 24
  • 28
  • Thank you for giving some code. It seems to be working, but can you do a quick explanation as to how. I just need help understanding the String{} vals = word.split("\\s+") and the parseInt methods. – ShiftyMcGrifty Feb 09 '13 at 01:47
  • @ShiftyMcGrifty I updated the answer and added few link which will give you more information. – Smit Feb 09 '13 at 01:54
  • Thank you very much, I was looking it up in the API right now. Looking over my assignment, I believe my professor was just asking for a output dialog box, which I was able to get. But learning this will be useful in the future. Once again, thanks! – ShiftyMcGrifty Feb 09 '13 at 01:58
  • 1
    @ShiftyMcGrifty I am glad it helped. If any of the following answer solved your issue then accept the answer and close the question. – Smit Feb 09 '13 at 01:59
2

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.

Name
  • 2,037
  • 3
  • 19
  • 28
  • I appreciate the help, while my professor is requiring that everything be in one class, and in the main, I understand what you're getting at. Definitely helpful for the future. – ShiftyMcGrifty Feb 09 '13 at 02:42