gangLand
gangLand

Reputation: 59

How do I stop my code from executing every println after I execute the right code?

    Scanner scan = new Scanner(System.in);

    System.out.print("Enter 2 numbers: ");
    int num1 = scan.nextInt();
    int num2 = scan.nextInt();
    System.out.println("Numbers Saved! Choose your operator + - * / ");
    String operator = scan.next();
    int result;

    result = (operator.equals("+")) ? (num1 + num2) : (num1);
    System.out.println("The addition result is " +result);
    result = (operator.equals("-")) ? (num1 - num2) : (num1);
    System.out.println("The subtraction result is " +result);
    result = (operator.equals("*")) ? (num1 * num2) : (num1);
    System.out.println("The multiplication result is " +result);
    result = (operator.equals("/")) ? (num1 / num2) : (num1);
    System.out.println("The division result is " +result);



}

} This is my simple calculator code, for example when i choose the + option, it runs all System.out.println lines, how do I prevent it from doing this and only execute the println that matches the operator?

Upvotes: 0

Views: 50

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201447

I would encapsulate the operator logic (resolution and evaluation) into an enum. Like,

enum Oper {
    ADDITION("+"), SUBTRACTION("-"), MULTIPLICATION("*"), DIVISION("/");
    Oper(String symbol) {
        this.symbol = symbol;
    }

    public int eval(int a, int b) {
        switch (this) {
        case ADDITION: return a + b;
        case SUBTRACTION: return a - b;
        case MULTIPLICATION: return a * b;
        case DIVISION: return a / b;
        }
        return -1;
    }

    private String symbol;

    public static Oper from(String operator) {
        for (Oper o : values()) {
            if (o.symbol.equals(operator)) {
                return o;
            }
        }
        return null;
    }
}

That simplifies the logic in main, just resolve the operator and evaluate it. Like,

Oper o = Oper.from(operator);
System.out.printf("The %s result is %d%n", o.name().toLowerCase(), o.eval(num1, num2));

Upvotes: 2

MWB
MWB

Reputation: 1879

Try a switch:

switch (operator) {
    case "+":
        result = num1 + num2;
        System.out.println("The addition result is " + result);
        break;
    case "-":
        result = num1 - num2;
        System.out.println("The subtraction result is " + result);
        break;
    case "-":
        result = num1 * num2;
        System.out.println("The multiplication result is " + result);
        break;
    case "/":
        result = num1 / num2;
        System.out.println("The integer division result is " + result);
        break;
    default:
        throw IllegalArgumentException("Unsupported operator: " + operator);
}

Upvotes: 2

Related Questions