Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Calculator {
- private double num1;
- private double num2;
- private double result;
- public void getInput() {
- Scanner scanner = new Scanner(System.in);
- System.out.print("Enter first number: ");
- num1 = scanner.nextDouble();
- System.out.print("Enter second number: ");
- num2 = scanner.nextDouble();
- }
- public void add() {
- result = num1 + num2;
- System.out.println("Result: " + result);
- }
- public void subtract() {
- result = num1 - num2;
- System.out.println("Result: " + result);
- }
- public void multiply() {
- result = num1 * num2;
- System.out.println("Result: " + result);
- }
- public void divide() {
- if (num2 != 0) {
- result = num1 / num2;
- System.out.println("Result: " + result);
- } else {
- System.out.println("Error: Division by zero is not allowed.");
- }
- }
- public static void main(String[] args) {
- Calculator calculator = new Calculator();
- calculator.getInput();
- System.out.println("Select an operation:");
- System.out.println("1. Addition");
- System.out.println("2. Subtraction");
- System.out.println("3. Multiplication");
- System.out.println("4. Division");
- Scanner scanner = new Scanner(System.in);
- int choice = scanner.nextInt();
- if (choice == 1) {
- calculator.add();
- } else if (choice == 2) {
- calculator.subtract();
- } else if (choice == 3) {
- calculator.multiply();
- } else if (choice == 4) {
- calculator.divide();
- } else {
- System.out.println("Invalid choice.");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement