This Java program implements a simple text-based calculator in the...

May 29, 2025 at 03:43 PM

package Case_Study_7; import java.util.Scanner; public class Calc { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("🔢 Java Calculator - Type 'exit' to quit"); while (true) { System.out.print("Enter expression (e.g., 5 + 3 or sqrt 9): "); String line = sc.nextLine(); if (line.equalsIgnoreCase("exit")) break; try { String[] tokens = line.split(" "); if (tokens.length == 1 && isNum(tokens[0])) { System.out.println("➡️ Result: " + tokens[0]); } else if (tokens.length == 2 && (tokens[0].matches("sqrt|log|sin|cos|tan"))) { double a = Double.parseDouble(tokens[1]); switch (tokens[0]) { case "sqrt" -> System.out.println("➡️ √" + a + " = " + Math.sqrt(a)); case "log" -> System.out.println("➡️ log(" + a + ") = " + Math.log(a)); case "sin" -> System.out.println("➡️ sin(" + a + ") = " + Math.sin(Math.toRadians(a))); case "cos" -> System.out.println("➡️ cos(" + a + ") = " + Math.cos(Math.toRadians(a))); case "tan" -> System.out.println("➡️ tan(" + a + ") = " + Math.tan(Math.toRadians(a))); } } else if (tokens.length == 3 && isNum(tokens[0]) && isOp(tokens[1]) && isNum(tokens[2])) { double a = Double.parseDouble(tokens[0]); double b = Double.parseDouble(tokens[2]); char op = tokens[1].charAt(0); double res = switch (op) { case '+' -> a + b; case '-' -> a - b; case '*' -> a * b; case '/' -> b != 0 ? a / b : Double.NaN; case '%' -> a % b; default -> Double.NaN; }; if (Double.isNaN(res)) System.out.println("⚠️ Error: Division by zero"); else System.out.printf("➡️ %s %c %s = %.4f%n", a, op, b, res); } else { System.out.println("❗ Invalid input. Try again."); } } catch (Exception e) { System.out.println("❌ Error: Invalid format. Use: num op num | func num"); } } System.out.println("👋 Goodbye!"); sc.close(); } static boolean isNum(String s) { try { Double.parseDouble(s); return true; } catch (NumberFormatException e) { return false; } } static boolean isOp(String s) { return s.matches("[+\\-*/%]"); } }

This Java program implements a simple text-based calculator in the Calc class. Here's an explanation of what the code does:

Purpose:

The program provides an interactive command-line calculator capable of:

  1. Calculating basic mathematical operations between two numbers (+, -, *, /, %).
  2. Performing some single operand operations (sqrt, log, sin, cos, tan).
  3. Handling invalid input gracefully with proper error messages.
  4. Repeating calculations in a loop until the user decides to exit by typing exit.

Detailed Explanation:

  1. Program Setup:

    • It imports the Scanner class to read user input.
    • Prompts the user with instructions:
      🔢 Java Calculator - Type 'exit' to quit
      
  2. Main Calculation Loop (while (true)):

    • Continuously reads input from the user until they type exit.
  3. Input Parsing and Processing:

    • Case 1: If the user inputs a single valid number, it echoes the number:
      ➡️ Result: <number>
      
    • Case 2: If the user inputs a unary operation (e.g., sqrt 9 or sin 45):
      • The program recognizes supported operations (sqrt, log, sin, cos, tan).
      • Parses the number and performs the operation using the Math library:
        • sqrt: Computes the square root.
        • log: Computes the natural logarithm.
        • sin, cos, tan: Trigonometric calculations using degrees (converted to radians).
      • Outputs the result.
    • Case 3: If the user inputs a binary operation (e.g., 5 + 3):
      • Splits the input into three parts: number1 operator number2.
      • Parses the numbers and checks if the operator is one of +, -, *, /, %.
      • Performs the operation:
        • Addition (+)
        • Subtraction (-)
        • Multiplication (*)
        • Division (/): Checks for division by zero and outputs appropriate error messages.
        • Modulus (%)
      • Outputs the result, formatted to 4 decimal places.
  4. Error Handling:

    • Misformatted or invalid inputs (e.g., abc, 5 ^ 2) are caught by:
      • A check on token lengths or valid functions/operators.
      • Catching exceptions when parsing or processing invalid inputs.
    • Outputs error messages:
      ❗ Invalid input. Try again.
      
  5. Exit Condition:

    • If the user types exit (case insensitive), the loop breaks, and the program outputs:
      👋 Goodbye!
      
    • The Scanner resource is closed.
  6. Helper Methods:

    • isNum(String s): Checks if the input is a valid numeric value by attempting to parse it as a double.
    • isOp(String s): Checks if the input is a valid mathematical operator (one of +, -, *, /, %).

Example Usage:

  1. Regular operations:

    Enter expression (e.g., 5 + 3 or sqrt 9): 5 + 3
    ➡️ 5.0 + 3.0 = 8.0000
    
  2. Unary operations:

    Enter expression (e.g., 5 + 3 or sqrt 9): sqrt 16
    ➡️ √16.0 = 4.0
    
  3. Trigonometric operation:

    Enter expression (e.g., 5 + 3 or sqrt 9): sin 30
    ➡️ sin(30.0) = 0.49999999999999994
    
  4. Division by zero:

    Enter expression (e.g., 5 + 3 or sqrt 9): 5 / 0
    ⚠️ Error: Division by zero
    
  5. Invalid inputs:

    Enter expression (e.g., 5 + 3 or sqrt 9): 5 ^ 2
    ❗ Invalid input. Try again.
    
  6. Exit:

    Enter expression (e.g., 5 + 3 or sqrt 9): exit
    👋 Goodbye!
    

Key Features:

  • Supports various mathematical calculations with input validation.
  • Handles common errors (e.g., invalid format, division by zero).
  • Provides user-friendly interaction with error and result messages.
  • Allows extensibility for new operations.
Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node