如果只有循环x-y工作,请给出答案

时间:2014-11-14 11:44:45

标签: java if-statement

在下面的JAVA代码中,Mul和Add运算符不能正常工作我得到的X-y运算符结果请建议如何找到这个问题的答案。

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);
}

}

3 个答案:

答案 0 :(得分:6)

在Java中,您不能将字符串与==进行比较,而是使用equalsmore):

if(op.equals("*"))

如果你正在使用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;
}

这不会在Java 6及更早版本中编译。

另外,as Bobby points out in a comment,您* + + if/else if switch操作中{{1}} {{1}}。 (已在上面的{{1}}中进行了更正。)

答案 1 :(得分:0)

正如其他人所指出的那样。在比较对象时,您应该使用.equals()而不是==。 (String是Java中的一个对象。)

使用==仅对原始数据类型进行比较,例如:intchardouble ..等等

由于您的运算符是单个字符,因此如果您将运算符的类型从String更改为char

,则代码仍然有效
void calculate(int x,int y, char op)
{
    //Your codes
}

答案 2 :(得分:0)

在java中,==不能用于比较字符串。改为使用.equals()方法。

if(op.equals("*"))
    System.out.println("X x Y : "+(x*y));
else if(op.equals("+"))
    System.out.println("X + Y : "+(x*y));
else
   System.out.println("X - Y : "+(x-y));