Using Arithmetic Operators
In these steps, you create a program that uses arithmetic operators.
1. Open a new file in your text editor, and type the import statement needed for interactive input wiht the Scanner class:
import java.util.Scanner;
2. Type the class header and its curly braces for a class named ArithmeticDemo. Within the class's curly braces, enter the main() method header and its braces.
public class ArithmeticDemo
{
public static void main(String[] args)
{
}
}
3. With the main() method, declare five int variables that will be used to hold two input values and their sum, difference, and average:
int firstNumber;
int secondNumber;
int sum;
int difference;
int average;
4. Also declare a Scanner object so that keyboard input can be accepted.
Scanner input = new Scanner(System.in);
5. Prompt the user for and accept two integers:
System.out.print("Please enter an integer>> ");
firstNumber = input.nextInt();
System.out.print("Please enter another integer>> ");
secondNumber = input.nextInt();
6. Add statements to perform the necessary arithmetic operations:
sum = firstNumber + secondNumber;
difference = firstNumber - secondNumber;
average = sum / 2;
7. Display the three calculated values:
System.out.println(firstNumber + " + " + secondNumber + " is " + sum);
System.out.println(firstNumber + " - " + secondNumber + " is " + difference);
System.out.println("The average of " + firstNumber + " and " + secondNumber + " is " + average);
8. Save the file as ArithmeticDemo.java, and then compile and execute it. Enter values of your choice. Figure 2-38 shows a typical execution. Notice that because integer division was used to compute the average, the answer is an integer.
Figure 2-38 Typical execution ArithmeticDemo application see image.
9. Execute the program multiple times using various integer values and confirm that the results are accurate.