Adding two Integers in Java Application
This
application reads (or inputs) two integers (whole
numbers,) typed by a user at the keyboard, computes their sum and displays it.
This program
Must
keep track of the numbers supplied by the user for the calculation later in the
program.
Programs
remember numbers and other data in the computer’s memory and access
That data through program
elements called variables.
Solution
//Addition program that displays the sum
of two numbers.
//Java packages
import javax.swing.JOptionPane;
//program uses JOptionPane
public class Addition{
//main method begins execution of java application
public static void main (String args[])
{
String firstNumber; //first string entered by user
String secondNumber; //second string entered by user
int number1; //first number to
add
int number2; //second number to
add
int sum; //sum of number1 and
number2
//read in first number from user as a string
firstNumber = JOptionPane.showInputDialog("Enter first
integer");
//read in second number from user as a string
secondNumber = JOptionPane.showInputDialog("Enter second interger");
//convert numbers from type string to type int
number1 = Integer.parseInt(firstNumber);
number2 = Integer.parseInt(secondNumber);
//add numbers
sum = number1 + number2;
//display result
JOptionPane.showMessageDialog(null, "The sum is " +sum, "Results",
JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
}
Comments
Post a Comment
Please feel free to comments if you have any ideas, questions and subjection concerning our post and programs