• Post Reply Bookmark Topic Watch Topic
  • New Topic

else/if problem  RSS feed

 
Preston Kruckow
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm having a problem with getting the wrong output in this program. Here is the code:

It compiles, but always prints out zsa-zsa every time.
 
Ryan McGuire
Ranch Hand
Posts: 1143
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You want to use single quotes around your character constants instead of double quotes.
 
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
Hi,

Welcome to JavaRanch!

You don't compare Strings using ==; you use the equals() method.

if (firstLetter.equals("e")) ...

The "==" operator asks if two objects are physically the same bit of memory; the equals() methods asks if two objects are "the same", which for Strings, means they have the same characters in the same order.
 
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
Originally posted by Ryan McGuire:
You want to use single quotes around your character constants instead of double quotes.


Nope -- then this wouldn't even compile! They're (correctly) Strings, not character constants.
 
Preston Kruckow
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alright I did that, but I'm still getting 25 errors when I compile it. Here is the revised code:

Currently 25 errors...
 
Preston Kruckow
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest, I did what you said, but now the compiler is complaining that variable first might not have been initialized.
 
Daniel Lucas
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alright, Preston (a friend in my AP Comp Sci A class) got it to work. He just initialized first to "adadada" and it started working correctly. Thanks for your help everyone!
 
Ryan McGuire
Ranch Hand
Posts: 1143
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:

Nope -- then this wouldn't even compile! They're (correctly) Strings, not character constants.


Oops, I didn't even look back at the type of firstLetter. I had just assumed from the if/else if's that it was a single character. That's what I get for responding BC (before coffee).
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!