This week's book giveaway is in the Agile forum.
We're giving away four copies of Head First Agile and have Andrew Stellman & Jennifer Greene on-line!
See this thread for details.
Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

If then else  RSS feed

 
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
Sheriff
Posts: 24217
38
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: 42972
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") )
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!