1

So basically, I'm trying to create a simple java calculator for the following functions but it seems my functions are not executing the way they're supposed (i.e. + not adding, - not subtracting). Would appreciate some help :)

    if (ope == "+") {
        //add
    } else if (ope == "-") {
        //subtract
    } else if (ope == "*") {
        //multiply
    } else if (ope == "/") {
        //divide
    }
}
Ted
  • 515
  • 1
  • 4
  • 14

2 Answers2

5

Incorrect String comparison, instead of:

if (ope == "+") {
} else if (ope == "-") {
} else if (ope == "*") {
} else if (ope == "/") {

you should have:

if ("+".equals(ope)) {
} else if ("-".equals(ope)) {
} else if ("*".equals(ope)) {
} else if ("/".equals(ope)) {
Adam Siemion
  • 15,569
  • 7
  • 58
  • 92
  • Thanks Adam, that fixed the operation problems although it seems after the first run (which is correct) any other operation after that gives invalid outputs..would you happen to know where the source of this problem is? edit: seems it might be to do with the clear function, not sure what it is causing it :S – Ted Jun 27 '13 at 10:29
0

In Java SE 7 and later, you can use a String object in the switch statement's expression. More info

if(ope != null)
{
 switch(ope)
 {
  case "+" : do1(); break;
  case "-" : do2(); break;
  case "*" : do3(); break;
  case "/" : do4(); break;
  default :  doDefault(); break;
 }
}

More info about String comparison

Community
  • 1
  • 1
Petros Tsialiamanis
  • 2,718
  • 2
  • 23
  • 35
  • I personally hate this feature because it leads to hardcoded values​​. It is much better to define the possible values in an "enum" ​​and they can also be used in the switch statement (and checked by the compiler) – Esteve Jun 27 '13 at 10:34