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.

Academic Honesty!
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly complete the form. Please provide a valid email address and we will get back to you within 24 hours. Payment is through PayPal, Buy me a Coffee or Cryptocurrency. We are a nonprofit organization however we need funds to keep this organization operating and to be able to complete our research and development projects.