集册 Java实例教程 迷你命令

迷你命令

欢马劈雪     最近更新时间:2020-01-02 10:19:05

458
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
迷你命令行计算器

import java.util.Arrays;/*N o w  J a v a  .   c o m*/


public class Main {

  public static void main(String[] args) {

    System.out.println(Arrays.toString(args));

    if (!(args.length == 3 && args[1].length() == 1)) {

      printUsage();

      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();
      /*
      时 代 J     a    v  a - nowjava.com 提 供
      */

      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(
展开阅读全文