Tuesday, February 12, 2013

Tutorial 11 : Entering input JOptionPane, Addition Example

Java Tutorials For Beginners, Tutorial 11 : Entering input JOptionPane, Addition Example.

Another way to get input is to use JOptionPane class. Previously I was using Scanner class.

To use it, add the import javax.swingJOptionPane ; statement .

To get input we use, the following code ,

JOptionPane.showInputDialog(null, "Enter 1st number", "Input Example", JOptionPane.QUESTION_MESSAGE);

The 1st argument as we use null, second to prompt user to enter the 1st number, the third is the title of input box and 4th causes icon ? question mark to appear.

To show the output, we use the following statement:

JOptionPane.showMessageDialog(null, "Total sum is : " + (x+y), "Input Example", JOptionPane.INFORMATION_MESSAGE );

The first normally we put null, second is the output, the third is the title of the dialog box and the 4th show the i icon in the message box.



Code


// Entering input using JOptionPane

import javax.swing.JOptionPane;

public class InputDialog{
public static void main(String[] args){

String number1 = JOptionPane.showInputDialog(null, "Enter 1st number", "Input Example", JOptionPane.QUESTION_MESSAGE);

//CONVERT STRING TO NUMBER

int x = Integer.parseInt(number1);

String number2 = JOptionPane.showInputDialog(null, "Enter 2nd number", "Input Example", JOptionPane.QUESTION_MESSAGE);

//CONVERT STRING TO NUMBER

int y = Integer.parseInt(number2);

//Show the output, summation

JOptionPane.showMessageDialog(null, "Total sum is : " + (x+y), "Input Example", JOptionPane.INFORMATION_MESSAGE );

}
}

No comments:

Post a Comment