Friday, 20 February 2015

Simple Maths Arithmetic using a switch statement

Now the following question was given to my students as a lab exercise.
The program should take 2 integers and an operand from the user and perform a maths arithmetic based on the operand supplied to the method by the user and here is the solution:


public class MathsSwich {

    public static void main(String[] args) {
        //testing the program
        compute(8, 3, "%");
    }

    public static void compute(int x, int y, String st) {

        switch (st) {
            case "+":
                System.out.println(x + " + " + y + " = " + (x + y));
                break;
            case "-":
                System.out.println(x + " - " + y + " = " + (x - y));
                break;
            case "/":
                System.out.println(x + " / " + y + " = " + (x / y));
                break;
            case "*":
                System.out.println(x + " * " + y + " = " + (x * y));
                break;
            case "%":
                System.out.println(x + " % " + y + " = " + (x % y));
                break;
            default:
                System.out.println("Please check operand!");

        }

    }

}

This is pretty straight forward as it is an alternative to the program i wrote using the if-else statements. Read it and understand it then testing using different scenarios. Happy Coding everyone!

0 comments:

Post a Comment