在下面的JAVA代码中,Mul和Add运算符不能只运行Xy运算符,我得到了建议如何找到这个问题的答案.
public class oppswithvalue {
void calculate(int x,int y,String op)
{
//System.out.println(op);
if(op=="*")
System.out.println("X x Y : "+(x*y));
else if(op=="+")
System.out.println("X + Y : "+(x*y));
else
System.out.println("X - Y : "+(x-y));
}
public static void main(String args[]) throws IOException
{
BufferedReader ar=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter first number : ");
int no1=Integer.parseInt(ar.readLine());
System.out.println("Enter Second number : ");
int no2=Integer.parseInt(ar.readLine());
System.out.println("Enter an operator : ");
String op=ar.readLine();
oppswithvalue tt= new oppswithvalue();
tt.calculate(no1, no2,op);
}
}
Run Code Online (Sandbox Code Playgroud)
在Java中,您不==使用equals(更多)比较字符串:
if(op.equals("*"))
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Java 7或更高版本,则可以在switch语句中使用字符串,这对于像这样的运算符列表是有意义的:
switch (op) {
case "*":
System.out.println("X x Y : "+(x*y));
break;
case "+":
System.out.println("X + Y : "+(x+y)); // <== Also see note below
break;
default:
System.out.println("X - Y : "+(x-y));
break;
}
Run Code Online (Sandbox Code Playgroud)
这不会在Java 6及更早版本中编译.
另外,正如Bobby在评论中指出的那样,你在操作中有*你想要的地方.(在上面已经纠正过了.)++if/else ifswitch