【问题标题】:Calculator without using more than 1 variable [closed]不使用超过 1 个变量的计算器 [关闭]
【发布时间】:2013-11-26 09:23:12
【问题描述】:
public class Calculator {
        Double x;
        /*
        * Chops up input on ' ' then decides whether to add or multiply.
        * If the string does not contain a valid format returns null.
        */
        public Double x(String x){
            x.split(" ");
            return new Double(0);
        }

        /*
        * Adds the parameter x to the instance variable x and returns the answer as a Double.
        */
        public Double x(Double x){
                System.out.println("== Adding ==");
                if (x(1).equals("+")){
                x = x(0) + x(2);
                }
                return new Double(0);
        }

        /*
        * Multiplies the parameter x by instance variable x and return the value as a Double.
        */
        public Double x(double x){
                System.out.println("== Multiplying ==");
                if(x(1).equals("x")){
                    x = x(0) * x(2);
                }
                return new Double(0);
        }

}

我试图拆分输入的双倍(“12 + 5”),使用“”拆分它,然后根据第二个值使其 + 或 x,然后将结果相加或乘以。以为我可以通过拆分和时间/添加来做到这一点,但没有用。

【问题讨论】:

  • 哎呀。你究竟想通过混合doubles 和Doubles 来达到什么目的,尤其是以这种非常违反直觉的方式?
  • 这是什么.. ??? :o
  • 我的意思不是不友善,但您的代码中基本上没有什么是正确的。白手起家。不要重复使用任何名称——也就是说,不要有三个名为 x 的函数、一个名为 x 的变量以及名为 x 的函数参数。
  • 重命名你的方法。这就像命名一本书Calculator 和章节x。你的问题陈述可能更清楚。包含示例总是好的。
  • 不幸的是,我必须同意@Ben。我越看你的代码,我就越困惑。你在哪里找到的?

标签: java calculator


【解决方案1】:

您似乎没有正确保存字符串拆分的结果。

x.split(" ");

返回一个字符串[],其中每个片段由“”分隔,例如

String x = "1 x 2";
String[] split = x.split(" ");

split[0] == "1";
split[1] == "x";
split[2] == "2";

您可能会受益于对您的方法和变量使用更具描述性的名称。

这样的事情可能会起作用:

public class Calculator {
    public static int result;

    public static void main(String[] args)
    {
        String expression = args[0];
        String[] terms = expression.split(" ");
        int firstNumber = Integer.parseInt(terms[0]);
        int secondNumber = Integer.parseInt(terms[2]);
        String operator = terms[1];

        switch (operator)
        {
            case "*":
                //multiply them
                break;
            case "+":
                //add them
                break;
            case "-":
                //subtract them
                break;
            case "/":
                //divide them
                break;
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 2016-04-04
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    相关资源
    最近更新 更多