java命令行计算器帮助数列相加

xcitsw88  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(317)

所以我在为课堂制作一个简单的计算器。我已经记下了它的大部分,但我有麻烦,因为它的声明,计算器后+需要一个数字序列的总和。我知道我需要对数组做些什么,但我不完全确定是什么。任何帮助或建议将不胜感激,谢谢!
输出示例:

java hw1.Calculator + 3 2 5.2 2 

sum: 12.2

到目前为止我的代码是:

public class Calculator3 {
  public static void main(String[] args) {

    if (args.length != 3) {
      System.out.println("Usage: java  Calculator3  double  op  double\n" +
                         "where op can be +, -, x, or /");
      System.exit(-1);                      
    }
    double d1 = 0.0, d2 = 0.0;
    try {
      d1 = Double.parseDouble(args[0]);
      d2 = Double.parseDouble(args[2]);
    }
    catch (Exception e) {
      // System.out.println(e);
      System.out.println("Error: at least one of the operands is not a number");
      System.exit(-2);
    }
    /*
    finally    {
     System.out.println("Finally clause executed. ");
    }
    */
    char op = args[1].charAt(0);
    double result = 0;
    switch (op) {
      default:
        System.out.println("Error: accepted operators are +, -, x, and /");
        System.exit(-3);
      case '+': 
        result = d1 + d2;
        break;
      case '-':
        result = d1 - d2;
        break;
      case 'x':
      case 'X':
        result = d1 * d2;
        break;
      case '/':
        result = d1 / d2;
        break;

    }
    System.out.println(d1 + " " + op + " " + d2 + " = " + result);
  }
}
hc8w905p

hc8w905p1#

你的方法只有两个数字。我想你的程序必须为几个数字服务,就像你说的,你必须对数组做些什么。
你有一个数组:

public static void main(String[] args)

把第一个参数作为运算,后面的所有参数都作为数字。
然后使用system.arraycopy(…)分隔操作数
然后可以将操作数数组(直到现在都是字符串)转换为数字。
然后您可以使用java8流来总结它。或者使用循环(https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/)
我希望这会有帮助,但我不想让你完成家庭作业。

相关问题