-8
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,然后添加或乘以结果。以为我可以通过拆分和时间/添加来做到这一点,但不起作用。

4

1 回答 1

2

看起来您没有正确保存字符串拆分的结果。

x.split(" ");

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

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;
        }
    }
}
于 2013-11-13T16:49:34.730 回答