Java 不使用多个变量的计算器
我正在尝试拆分双输入(“12+5”)使用“”拆分,然后根据第二个值将其设为+或x,然后将结果相加或乘以。我以为我可以通过拆分和时间/添加来完成,但没有起作用。看起来您没有正确保存字符串拆分的结果Java 不使用多个变量的计算器,java,calculator,Java,Calculator,我正在尝试拆分双输入(“12+5”)使用“”拆分,然后根据第二个值将其设为+或x,然后将结果相加或乘以。我以为我可以通过拆分和时间/添加来完成,但没有起作用。看起来您没有正确保存字符串拆分的结果 public class Calculator { Double x; /* * Chops up input on ' ' then decides whether to add or multiply. * If the string
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);
}
}
返回一个字符串[],其中每个片段由“”分隔,例如
对方法和变量使用更具描述性的名称可能会使您受益匪浅
类似的方法可能会奏效:
String x = "1 x 2";
String[] split = x.split(" ");
split[0] == "1";
split[1] == "x";
split[2] == "2";
哎呀。通过混合
double
s和double
s,特别是以一种非常违反直觉的方式,您到底想要实现什么?这是什么oI并不意味着不友善,但是在你的代码中基本上没有什么是错误的。从头开始。不要重用任何名称——也就是说,不要有三个名为x
的函数,也不要有一个名为x
的变量和名为x
的函数参数。重命名方法。这就像给一本书命名Calculator
和章节x
。你的问题陈述会更清楚。举例总是好的。不幸的是,我不得不同意@Ben的观点。我看你的代码越多,我就越糊涂。你在哪里找到的?
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;
}
}
}