简体   繁体   中英

Replacing multiple if statements with a single if statement

My code is supposed to take a string and if this string == "Help" it will do task X and if this string = "10.0.0.i", it will do task Y. Here is the code:

if(message.equals("Help")) {
                            //do X
}
else if ((message.equals("10.0.0.1")){
                                //do Y
    }
else if ((message.equals("10.0.0.2")){
                                //do Y
    }
else if ((message.equals("10.0.0.3")){
                                //do Y
    }
else if ((message.equals("10.0.0.4")){
                                //do Y
    }
.
.
.

I'm new to java. Since in message = "10.0.0.i" only the last character is changing and this code is going to implement task Y for all of them, I want to know if it's possible to replace all these conditionals statements if ((message.equals("10.0.0.i")) with a single "if" (instead of writing separate if s for "10.0.0.1", "10.0.0.2" etc.).

If only the last character is changing for messages starting with "10.0.0", you could use startsWith() for the other cases than "Help":

if (message.equals("Help")) {
   //do X
} else if (message.startsWith("10.0.0")){
   //do Y
}

One option is to use a regular expression:

if ((message.matches("10\\.0\\.0\\.[1234]")) {
    // do Y
}

There is another option with type casting.

    int i=9;

    if(message.equals("Help")) {
                        //do X
    }else if ((message.equals("10.0.0."+String.valueOf(i))){
                        //do Y
    }

Guys you are getting overly complicated with this solution. If it says help do x, if it says something else do y

if(message.equals("Help")) {
                        //do X
}
else {
    //do y
}

he didn't say that y had to do 100 different things only that everything other than help had to do y. so a very simple if/else statement is all that is needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM