Abdul Ahmad Abdul Ahmad - 6 months ago 17
Java Question

Result based on UserInput

User input giving strange result in code... edited

Answer

First, there are a lot of bad things in your code, and this may be not the best version of how it should look like, but anyway it is much better. It would be good for you to use switch operator, and you can declare some static final variables for operations you need to do. Declare class that will have some math tools in it this static methods and fiels:

public class MathTool {
    public static final int PLUS_OPERATION = 0;

    public static final int MINUS_OPERATION = 1;

    public static final int MULTIPLY_OPERATION = 2;

    public static final int DIVIDE_OPERATION = 3;

    public static double doMathOperation(double digit1, double digit2, int operation) {
        switch (operation) {
        case PLUS_OPERATION: return digit1 + digit2;
        case MINUS_OPERATION: return digit1 - digit2;
        case MULTIPLY_OPERATION: return digit1 * digit2;
        case DIVIDE_OPERATION: return digit1 / digit2;
        default: return 0;
        }
    }
}

Then you can just call its methods like this:

    public static void main(String[] args) {
        double operationResult = MathTool.doMathOperation(5, 3, MathTool.MULTIPLY_OPERATION);
        System.out.println(operationResult);
    }

And in Java you should use lowercase as first letter for variable name.

EDIT:

For user input from console use Scanner like this:

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
Comments