A Mini Command-line Calculator - Java Object Oriented Design

Java examples for Object Oriented Design:main method

Description

A Mini Command-line Calculator

Demo Code

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    System.out.println(Arrays.toString(args));
    if (!(args.length == 3 && args[1].length() == 1)) {
      printUsage();/*from  w  w  w  .  j  a  v  a2s .co  m*/
      return;
    }
    double n1 = 0.0;
    double n2 = 0.0;
    try {
      n1 = Double.parseDouble(args[0]);
      n2 = Double.parseDouble(args[2]);
    } catch (NumberFormatException e) {
      System.out.println("Both operands must be a number");
      printUsage();
      return; // Stop the program here
    }

    String operation = args[1];
    double result = compute(n1, n2, operation);

    // Print the result
    System.out.println(args[0] + args[1] + args[2] + "=" + result);
  }

  public static double compute(double n1, double n2, String operation) {
    double result = Double.NaN;
    switch (operation) {
    case "+":
      result = n1 + n2;
      break;
    case "-":
      result = n1 - n2;
      break;
    case "*":
      result = n1 * n2;
      break;
    case "/":
      result = n1 / n2;
      break;
    default:
      System.out.println("Invalid operation:" + operation);
    }
    return result;
  }

  public static void printUsage() {
    System.out.println("Usage: java Main expr");
    System.out.println("Where expr could be:");
    System.out.println("n1 + n1");
    System.out.println("n1 - n2");
    System.out.println("n1 * n2");
    System.out.println("n1 / n2");
    System.out.println("n1 and n2 are two numbers");
  }
}

Result


Related Tutorials