• Post Reply Bookmark Topic Watch Topic
  • New Topic

NoBrainer...why dosen't it work?  RSS feed

 
Andrea Corbally
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, I have a simple if statement and in watch window it is true, but it is failing. Here it is (simplified of course). You tell me what is wrong. Thanks in advance. my is a string of "-FEB-2003". Mnth is "FEB"

mnth = my.substring(1,4); // get month
if (mnth == "JAN") {
int m = 01;
}
else if(mnth == "FEB"){
int m = 02;
}
else if(mnth == "NOV"){
int m = 11;
}
else if(mnth == "DEC"){
int m = 12;
}
else {
System.out.println("MNTH is not valid: "+mnth);
}
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try using equals() rather than ==. Or try
mnth = my.substring(1,4).intern();
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One should get in the habit of always using .equals() to compare Strings.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I always look for ways to eliminate if-else chains. Maybe
int monthNumber = 1 + myVector.indexOf( monthName );
int monthNumber = 1 + ( "JAN FEB MAR APR ...".indexOf(MonthName) / 4 );
Any other ideas?
 
Andrea Corbally
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone for the suggestions. I am having difficulty adjusting to OOP. Thanks again!!
 
VIJAY Yadlapati
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Never use == to compare objects. Rather use equals(). If equals() is not implemented in any of the ancestors, then Object.equals() - which uses == will be called.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Never use == to compare objects
Unless, of course, you're sure you know what you're doing.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!