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,然后添加或计算结果。我以为我可以通过拆分和时间/添加来实现它但不起作用。
答案 0 :(得分: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;
}
}
}