In: Computer Science
Begin by creating a Java project with one class – Addition. Start with the class Addition as shown in Figure 12.2. This program uses dialog boxes for I/O to get two integers and display the result of adding them together. The program should run “as is”. Change the program so that it gets and adds two doubles instead of integers. When that is working get a third double using a dialog box. Add the three doubles together, and display the result in a dialog box.
// Fig. 12.2: Addition.java
// Addition program that uses JOptionPane for input and
output.
import javax.swing.JOptionPane;
public class Addition
{
public static void main(String[] args)
{
// obtain user input from JOptionPane input dialogs
String firstNumber =
JOptionPane.showInputDialog("Enter first integer");
String secondNumber =
JOptionPane.showInputDialog("Enter second integer");
// convert String inputs to int values for use in a
calculation
int number1 = Integer.parseInt(firstNumber);
int number2 = Integer.parseInt(secondNumber);
int sum = number1 + number2; // add numbers
// display result in a JOptionPane message dialog
JOptionPane.showMessageDialog(null, "The sum is " + sum,
"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE);
}
} // end class Addition
// Fig. 12.2: Addition.java // Addition program that uses JOptionPane for input and output. import javax.swing.JOptionPane; public class Addition { public static void main(String[] args) { // obtain user input from JOptionPane input dialogs String firstNumber = JOptionPane.showInputDialog("Enter first integer"); String secondNumber = JOptionPane.showInputDialog("Enter second integer"); String thirdNumber = JOptionPane.showInputDialog("Enter third integer"); // convert String inputs to int values for use in a calculation double number1 = Double.parseDouble(firstNumber); double number2 = Double.parseDouble(secondNumber); double number3 = Double.parseDouble(thirdNumber); double sum = number1 + number2 + number3; // add numbers // display result in a JOptionPane message dialog JOptionPane.showMessageDialog(null, "The sum is " + sum, "Sum of Three Doubles", JOptionPane.PLAIN_MESSAGE); } } // end class Addition