Basic condensation code using || string operator

I am new to Java programming. I could not find any information regarding the use of || operator with strings. I was wondering if there was a more efficient way to make this code, in particular, which was still easy to read. I tried to make a simple calculator as a way to familiarize myself with IfThenElse statements.

    import java.util.Scanner;
     public class SimpleCalculator {
        public static void main(String[] args){
            Scanner input=new Scanner(System.in);
            double first;
            double second;
            String option;

            while(true){
                System.out.println("What function would you like to calculate?");
                option=input.next();    
                    if(option.equals("add") || option.equals("+")){
                        System.out.println("First number");
                        first=input.nextDouble();
                        System.out.println("Second number");
                        second=input.nextDouble();
                        double add=first+second;
                        System.out.println(add);
                    }
                    else if(option.equals("subtract") || option.equals("-")) {
                        System.out.println("First number");
                        first=input.nextDouble();
                        System.out.println("Second number");
                        second=input.nextDouble();
                        double subtract=first-second;
                        System.out.println(subtract);
                    }
                    else if(option.equals("multiply") ||option.equals("*")) {
                        System.out.println("First number");
                        first=input.nextDouble();
                        System.out.println("Second number");
                        second=input.nextDouble();
                        double multiply=first*second;
                        System.out.println(multiply);
                    }
                    else if(option.equals("divide") || option.equals("/"))  {
                        System.out.println("First number");
                        first=input.nextDouble();
                        System.out.println("Second number");
                        second=input.nextDouble();
                        double divide=first/second;
                        System.out.println(divide);
                    }
                    else if(option.equals("end")){
                        System.exit(0);
                }
            }
        }
    }

      

Most of the time I'm curious about the requirements I've tested and they actually work, but I find it a little awkward. However, any criticism would be appreciated.

+3


source to share


3 answers


Switch / case statements are a good alternative to the ifs series and as of Java 7 , you can use switch statements with strings. Note the syntactic difference between the two. Instead of grouping objects with curly braces, each case ends with a statement break

.

switch (option) {
    case "add":
    case "+":
        System.out.println("First number");
        first=input.nextDouble();
        System.out.println("Second number");
        second=input.nextDouble();
        double add=first+second;
        System.out.println(add);

        break;

    case "subtract":
    case "-":
        System.out.println("First number");
        first=input.nextDouble();
        System.out.println("Second number");
        second=input.nextDouble();
        double subtract=first-second;
        System.out.println(subtract);

        break;

    case "multiply":
    case "*":
        System.out.println("First number");
        first=input.nextDouble();
        System.out.println("Second number");
        second=input.nextDouble();
        double multiply=first*second;
        System.out.println(multiply);

        break;

    case "divide":
    case "/":
        System.out.println("First number");
        first=input.nextDouble();
        System.out.println("Second number");
        second=input.nextDouble();
        double divide=first/second;
        System.out.println(divide);

        break;

    case "end":
        System.exit(0);
}

      

Then I would suggest merging the duplicate invitation code. If you find yourself copying and pasting code, it's usually a good idea to take a step back and figure out how to avoid repetition. Duplicate code is a sign that you should refactor.



if (option.equals("end")) {
    System.exit(0);
}

System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();

switch (option) {
    case "add":
    case "+":
        double add=first+second;
        System.out.println(add);
        break;

    case "subtract":
    case "-":
        double subtract=first-second;
        System.out.println(subtract);
        break;

    case "multiply":
    case "*":
        double multiply=first*second;
        System.out.println(multiply);
        break;

    case "divide":
    case "/":
        double divide=first/second;
        System.out.println(divide);
        break;
}

      

In addition, you can also eliminate duplicate printouts by using one variable result

for all calculations.

if (option.equals("end")) {
    System.exit(0);
}

System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();

double result;

switch (option) {
    case "add":      case "+": result = first + second; break;
    case "subtract": case "-": result = first - second; break;
    case "multiply": case "*": result = first * second; break;
    case "divide":   case "/": result = first / second; break;
}

System.out.println(result);

      

+8


source


You use ||

it seems good to me. However, I have some general suggestions to make the code more complete.

First of all, why not have functions isAdd

, isSubtract

etc.? For example:

private boolean isAdd(String input){
    return input.equalsIgnoreCase("add") || input.equals("+");
}

      

The same applies to other operators. Than you can have code like:

if (isAdd(option)) ...

      

Which is more readable than

if (input.equalsIgnoreCase("add") || input.equals("+")) ...

      



In a larger program, you may need to check these things a few times and then have a way to do it becomes very convenient. Also, this way, if you want to change the definition of "add" (for example, now "a" also qualifies), you change the code in one place and the whole program matches.

Second, why not pipe out the bodies of these operators if

to other functions? Than your code would look like:

if (isAdd(option))
    performAddition();
else if (isSubtract(option))
    performSubtraction();
// .. etc

// function definitions here

      

Making a program more readable than what you have.

Third, take note of where you put your spaces. option = input.next()

looks better than option=input.next()

.

That's pretty much it. Good luck :)

+2


source


John Kugelman and Aviv Kohn gave good advice. I would like to add that your application will throw InputMismatchException

if you don't enter a valid number when calling nextDouble()

. Instead of your program terminating due to an exception, you can prompt the user to enter a valid number, after which he / she can try again.

One way to do this is to add the following methods to SimpleCalculator

:

    private static Double getValidNumber()
    {
        Double nr = null;
        while( nr == null )
        {
            nr = getNextDouble();
            if(nr == null) System.out.println("Please enter a valid number.");
        }
        return nr;
    }

    private static Double getNextDouble()
    {
        Scanner input=new Scanner(System.in);
        Double output = null;
        try{ output = input.nextDouble(); }catch(InputMismatchException e){}
        return output;
    }

      

Then in the main method, just replace the calls to input.nextDouble()

with getValidNumber()

.

+1


source







All Articles