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

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

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

  1. java hw1.Calculator + 3 2 5.2 2
  2. sum: 12.2

到目前为止我的代码是:

  1. public class Calculator3 {
  2. public static void main(String[] args) {
  3. if (args.length != 3) {
  4. System.out.println("Usage: java Calculator3 double op double\n" +
  5. "where op can be +, -, x, or /");
  6. System.exit(-1);
  7. }
  8. double d1 = 0.0, d2 = 0.0;
  9. try {
  10. d1 = Double.parseDouble(args[0]);
  11. d2 = Double.parseDouble(args[2]);
  12. }
  13. catch (Exception e) {
  14. // System.out.println(e);
  15. System.out.println("Error: at least one of the operands is not a number");
  16. System.exit(-2);
  17. }
  18. /*
  19. finally {
  20. System.out.println("Finally clause executed. ");
  21. }
  22. */
  23. char op = args[1].charAt(0);
  24. double result = 0;
  25. switch (op) {
  26. default:
  27. System.out.println("Error: accepted operators are +, -, x, and /");
  28. System.exit(-3);
  29. case '+':
  30. result = d1 + d2;
  31. break;
  32. case '-':
  33. result = d1 - d2;
  34. break;
  35. case 'x':
  36. case 'X':
  37. result = d1 * d2;
  38. break;
  39. case '/':
  40. result = d1 / d2;
  41. break;
  42. }
  43. System.out.println(d1 + " " + op + " " + d2 + " = " + result);
  44. }
  45. }
hc8w905p

hc8w905p1#

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

  1. public static void main(String[] args)

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

相关问题