JAVA Using the static keyword, define an abstract class called Calculator that h
ID: 3875542 • Letter: J
Question
JAVA
Using the static keyword, define an abstract class called Calculator that has four methods; add, subtract, divide and multiply. Each method should be defined to take two numbers as arguments, perform a calculation on the numbers, and return a result.
Using the if-then- else statement, write a program that accepts user inputs. The program should ask a user to type two numbers and choose an option to add, subtract, divide or multiply the numbers. Whenever the user chooses the correct option, the program should invoke an appropriate method of the Calculator class and display its result.
Explanation / Answer
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Simple Calculator");
System.out.println(" Here are your options:");
System.out.println(" 1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Division");
System.out.println("4. Multiplication");
System.out.print(" What would you like to do?: ");
int choice = kb.nextInt();
System.out.println();
if (choice == 1){
addition();
}
else if (choice == 2){
subtraction();
}
else if (choice == 3){
division();
}
else if (choice == 4){
multiplication();
}
System.out.println();
kb.close();
}
public static void addition(){
int nOne, nTwo;
Scanner kb = new Scanner(System.in);
System.out.println("Addition");
System.out.print(" First Number: ");
nOne = kb.nextInt();
System.out.print(" Second Number: ");
nTwo = kb.nextInt();
kb.close();
System.out.println(" Sum: " + nOne + " + " + nTwo + " = " + (nOne + nTwo));
}
public static void subtraction(){
int nOne, nTwo;
Scanner kb = new Scanner(System.in);
System.out.println("Subtraction");
System.out.print(" First Number: ");
nOne = kb.nextInt();
System.out.print(" Second Number: ");
nTwo = kb.nextInt();
kb.close();
System.out.println(" Sum: " + nOne + " - " + nTwo + " = " + (nOne - nTwo));
}
public static void division(){
int nOne, nTwo;
Scanner kb = new Scanner(System.in);
System.out.println("Division");
System.out.print(" First Number: ");
nOne = kb.nextInt();
System.out.print(" Second Number: ");
nTwo = kb.nextInt();
kb.close();
System.out.println(" Sum: " + nOne + " / " + nTwo + " = " + (nOne / nTwo));
}
public static void multiplication(){
int nOne, nTwo;
Scanner kb = new Scanner(System.in);
System.out.println("Multiplication");
System.out.print(" First Number: ");
nOne = kb.nextInt();
System.out.print(" Second Number: ");
nTwo = kb.nextInt();
kb.close();
System.out.println(" Sum: " + nOne + " x " + nTwo + " = " + (nOne * nTwo));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.