Search code examples
javaswingjoptionpane

JOptionPane and reading integers - Beginner Java


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!


Solution

  • 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