Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

If then else

 
Raj kalaria
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi , I am new to java world and this might be a basic question

i want to use the below if statement in
negation form that is : if the columnname is not equal to score or summary then print not equal ( i dont want else)
----------------------------------------------------------

String columns_name = "title";
// trying to negate but this is a syntax error
if !(columns_name.equals("score")|| columns_name.equals("summary"))

{
System.out.println(" NotEqual");
}


else
{System.out.println("Equal");
}
-----------------------------------------------------------------

this works


String columns_name = "title";
if (columns_name.equals("score")|| columns_name.equals("summary"))

{
System.out.println(" Equal");
}


else
{System.out.println("Not Equal");
}
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The whole condition has to go inside the parentheses. Also be careful that the "!" means what you want, and that it applies to everything you want it to.

For example: here the "!" applies only to the first "equals()":

if (!columns_name.equals("score")|| columns_name.equals("summary"))

Here, it applies to both because of the extra parentheses:

if (!(columns_name.equals("score") || columns_name.equals("summary")))
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if !(columns_name.equals("score")|| columns_name.equals("summary"))

Just put parentheses around it like so:

if ( ! (columns_name.equals("score") || columns_name.equals("summary")))
 
Raj kalaria
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sometime soon you'll bump into boolean algebra. Here's one transform that may interest you right now:

not ( A or B ) == not A and not B

See if this is easier to read ... or not ...

if ( !columns_name.equals("score") && !columns_name.equals("summary") )

Either way is kind of twisty. I'd be tempted to reverse the if and else blocks to write

if ( columns_name.equals("score") || columns_name.equals("summary") )
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic