Home > database >  Checking user inputs for a calculator
Checking user inputs for a calculator

Time:10-13

I'm trying to code a validation method for a calculator, namely: I want to make sure a user inputs , -, /, * or %, keeping them in a loop until the correct input is made. Here's the "template" of the code:

public static String calcOperationType(){
    String input = scanner.next();
    String operator = "";
    switch (input){
        case(" "):
            operator = " ";
        break;
        case("-"):
            operator = "-";
        break;
        case("*"):
            operator = "*";
        break;
        case("/"):
            operator = "/";
        break;
        case("%"):
            operator = "%";
        break;
        default:
            System.out.println("This is not a valid operator, please input  , -, *, /, %");
            calcOperationType();
    }
    return operator;
}

The problem I'm facing here is that the value of operator is not reset when the correct input is made. For example, I input some value, and it sends me into a loop, I input some text on the second attempt, then I input one of the expected chars and the value I get is "" (blank). So from what I understand, the issue lies in reassigning the values from the switch statement to the return statement of the method. Is there any way to do it, or should I go for getters and setters?

CodePudding user response:

In the default case, change calcOperationType(); to return calcOperationType();

Your original solution's only return statement is return operator;

Operator is empty within the scope of the recursive function, so it returns an empty string

Edit: I also agree that you should use a While loop

public static String calcOperationType(){       
    String operator = scanner.next();
    
    while !(operator.equals(" ") || operator.equals("-") || operator.equals("*") || operator.equals("/") || operator.equals("%")){
        System.out.println("This is not a valid operator, please input  , -, *, /, %");
        operator = scanner.next();
    }
    
    return operator;
}

As shown above, you don't need a separate input and operator

CodePudding user response:

I hope this solves your issue.

    public static String calcOperationType(){
    String operator = "";
    while(true){
        String input = scanner.next();

        switch (input){
            case(" "):
            case("-"):
            case("*"):
            case("/"):
            case("%"): operator = input;
                        return operator;
            default:
                System.out.println("This is not a valid operator, please input  , -, *, /, %");    
        }
    }
}

If you have any doubt please let me know.

  • Related