【问题标题】:Java Command-Line Calculator Help. Adding a Sequences of NumbersJava 命令行计算器帮助。添加数字序列
【发布时间】:2020-09-07 05:11:00
【问题描述】:

所以我正在为课堂构建一个简单的计算器。我已经记下了大部分内容,但我遇到了麻烦,因为据说 + 之后的计算器需要对一系列数字求和。我知道我需要对数组做一些事情,但我不完全确定是什么。任何帮助或建议将不胜感激,谢谢!

输出示例:

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);
  }
}

【问题讨论】:

  • 您的代码做了一些完全不同的事情:它使用两个操作数(如“a+b=c”)解决了基本操作,您要求做其他事情。 Stackoverflow 不是要求您解决家庭作业的地方,除非您“真诚地尝试自己先解决问题”,如元堆栈规则 meta.stackoverflow.com/questions/334822/… 中所述

标签: java arrays switch-statement calculator


【解决方案1】:

您的方法仅适用于 2 个数字。 我想你的程序必须像你说的那样为多个数字服务,你必须对数组做一些事情。

你有一个数组:

public static void main(String[] args)
  • 将第一个参数作为运算,后面的所有参数作为数字。
  • 然后使用 System.arraycopy(...) 来分隔操作数
  • 然后您可以将操作数数组(到目前为止是字符串)转换为数字。
  • 那么您可以使用 java8 流来总结它。或者,您使用循环。 (https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/)

希望对你有帮助,但我不想帮你完成作业。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 2012-11-27
    • 2011-10-31
    相关资源
    最近更新 更多