0

Possible Duplicate:
Switch without break

I am making a small calculator app, and when the calculate button is clicked, a switch statement runs, but the number produced is not what It should be, I have tested my inputs and they do work here is the switch statement:

switch (currentOp) 
{
    case "+" : 
        answer = Float.toString(inp1 + inp2);
    case "-" : 
        answer = Float.toString(inp1 - inp2);
    case "X" : 
        answer = Float.toString(inp1 * inp2);
    case "/" : 
        answer = Float.toString(inp1 / inp2);
}
Community
  • 1
  • 1
CodeLover
  • 977
  • 3
  • 9
  • 14

3 Answers3

10

Just an addition to the other answer, using polymorphism is usually preferred to switch cases:

public enum Operation {
    ADDITION {
        @Override
        public float compute(float a, float b) {
            return a + b;
        }
    },
    SUBTRACTION {
        @Override
        public float compute(float a, float b) {
            return a - b;
        }
    },
    PRODUCT {
        @Override
        public float compute(float a, float b) {
            return a * b;
        }
    },
    DIVISION {
        @Override
        public float compute(float a, float b) {
            return a / b;
        }
    };

    public abstract float compute(float a, float b);
}

...

answer = currentOp.compute(inp1, inp2);
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
8

You forgot to break so your case statements are falling through. Try this:

case "+" : answer = Float.toString(inp1 + inp2); break;
case "-" : answer = Float.toString(inp1 - inp2); break;
case "X" : answer = Float.toString(inp1 * inp2); break;
case "/" : answer = Float.toString(inp1 / inp2); break;

Related documentation

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
7

See case fallthrough. If you don't break between each case, the next will be executed as well until a break is reached.

The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.

Tim M.
  • 53,671
  • 14
  • 120
  • 163