简体   繁体   中英

Check the value should be only 0 or 1, only using if block

How to print this statement without else block

String val ="0";
if( val.equals("0") || val.equals("1"))
{
    // Do nothing
}else{
    System.our.println("Value should be either 0 or 1");
}
String val ="0";
if( !val.equals("0") && !val.equals("1"))
{
   System.our.println("Value should be either 0 or 1");
}

Below condition will do the trick:

if( !val.equals("0") && !val.equals("1"))
{
    System.our.println("Value should be either 0 or 1");
}

If you want to achieve it using ||operators as mentioned in your question, then, simply add ! symbol in the beginning,

String val ="0";
if(!(val.equals("0") || val.equals("1"))){
    System.our.println("Value should be either 0 or 1");
}

The answer is indeed:

if( !val.equals("0") && !val.equals("1"))
{
   System.our.println("Value should be either 0 or 1");
}

But how do you get to it? You want to enter the else branch of your statement so, you negate it.

val.equals() negated becomes !val.equals()

Logically OR negated becomes AND (and viceversa) so: || becomes &&

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