0

In the below JAVA code Mul and Add operators are not working only X-y operator result i am getting please advice how to find the answer for this problem.

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

}
Bobby
  • 2,830
  • 3
  • 19
  • 36
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Kenster Nov 14 '14 at 12:30

3 Answers3

6

In Java, you don't compare strings with ==, you use equals (more):

if(op.equals("*"))

If you're using Java 7 or higher, you can use strings in switch statements, which would make sense for a list of operators like that:

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

This wouldn't compile in Java 6 and earlier.

Separately, as Bobby points out in a comment, you have * where you want + in the + operation in your if/else if. (It's corrected in the switch above.)

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

As others have pointed out. You should use .equals() instead of == when comparing objects. (String is an object in Java).

Use == for comparison only for primitive data types such as: int, char, double ..etc

Since your operator is a single character, your code can still work if you change the type of the operator from String to char

void calculate(int x,int y, char op)
{
    //Your codes
}
user3437460
  • 17,253
  • 15
  • 58
  • 106
0

In java,== can not be used for comparing Strings. Use .equals() method instead.

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));
PKG
  • 291
  • 1
  • 4
  • 16