Solution - Arithmetic calculation
Problem.
Write a Java program that prompts the user to enter two integers, and then displays the sum, difference, product, and quotient of the two numbers. Use a method to perform the calculation and display the results.
Solution.
ArithmeticOperations.java
import java.util.Scanner;
public class ArithmeticOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first integer: ");
int num1 = scanner.nextInt();
System.out.print("Enter second integer: ");
int num2 = scanner.nextInt();
performArithmetic(num1, num2); // 将计算和显示的任务分配给performArithmetic()方法,这里只调用
}
public static void performArithmetic(int num1, int num2) {
int sum = num1 + num2;
int difference = num1 - num2;
int product = num1 * num2;
double quotient = num1 / (double)num2;
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);
}
}