import javax.swing.*; // swing is a library of GUI components // example of using message boxes to get input and show output public class GUI_IO { // use input dialog to get user input public static int getInt(String msg) { boolean first = true; boolean done = false; // keep trying until we get a valid int // (loop actually ends when we return the number at the end of try) while (!done) { try { // showInputDialog returns a string // which we then try to parse as int to get our result // if user input not an int, exception is thrown String user = JOptionPane.showInputDialog(msg); int value = Integer.parseInt( user ); done = true; return value; // often we'd do this all in one line: //return Integer.parseInt( JOptionPane.showInputDialog(msg) ); } catch(NumberFormatException e) { // add nasty note after first bad input if (first) { msg = "Invalid, please enter an integer.\n" + msg; first = false; } } } } // get two ints and show a message with the sum. public static void main(String[] args) { // short version of message dialog JOptionPane.showMessageDialog(null, "WELCOME"); // calling method above to get input int n1 = getInt("What is the first number?"); int n2 = getInt("What is the second number?"); // long version of message dialog JOptionPane.showMessageDialog( null, // parent window to center over -- none here n1 + " + " + n2 + " = " + (n1 + n2), // output to show "Result", // message box title JOptionPane.INFORMATION_MESSAGE); // message box style // PLAIN_MESSAGE, INFORMATION_MESSAGE, ERROR_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE } }