Advertisement
LynchzDEV

Simple Calculator

Jul 2nd, 2023
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.82 KB | Source Code | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Calculator {
  4.     private double num1;
  5.     private double num2;
  6.     private double result;
  7.  
  8.     public void getInput() {
  9.         Scanner scanner = new Scanner(System.in);
  10.        
  11.         System.out.print("Enter first number: ");
  12.         num1 = scanner.nextDouble();
  13.        
  14.         System.out.print("Enter second number: ");
  15.         num2 = scanner.nextDouble();
  16.     }
  17.  
  18.     public void add() {
  19.         result = num1 + num2;
  20.         System.out.println("Result: " + result);
  21.     }
  22.  
  23.     public void subtract() {
  24.         result = num1 - num2;
  25.         System.out.println("Result: " + result);
  26.     }
  27.  
  28.     public void multiply() {
  29.         result = num1 * num2;
  30.         System.out.println("Result: " + result);
  31.     }
  32.  
  33.     public void divide() {
  34.         if (num2 != 0) {
  35.             result = num1 / num2;
  36.             System.out.println("Result: " + result);
  37.         } else {
  38.             System.out.println("Error: Division by zero is not allowed.");
  39.         }
  40.     }
  41.  
  42.     public static void main(String[] args) {
  43.         Calculator calculator = new Calculator();
  44.         calculator.getInput();
  45.  
  46.         System.out.println("Select an operation:");
  47.         System.out.println("1. Addition");
  48.         System.out.println("2. Subtraction");
  49.         System.out.println("3. Multiplication");
  50.         System.out.println("4. Division");
  51.  
  52.         Scanner scanner = new Scanner(System.in);
  53.         int choice = scanner.nextInt();
  54.  
  55.         if (choice == 1) {
  56.             calculator.add();
  57.         } else if (choice == 2) {
  58.             calculator.subtract();
  59.         } else if (choice == 3) {
  60.             calculator.multiply();
  61.         } else if (choice == 4) {
  62.             calculator.divide();
  63.         } else {
  64.             System.out.println("Invalid choice.");
  65.         }
  66.     }
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement