Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Testing a string from a scanner input in an if/else statement

 
Dwaine McMaugh
Greenhorn
Posts: 4
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I have just taught myself how to use the Scanner class but I cannot successfully test the user input in an if/else statement.

I am simply asking the user their gender in the format M or F. I want to test their input and display Male or Female.

Here is my code;



My output is;

Are you male or female? (format: M or F)
M
This is the user input

M
This is the debugging line showing the input as the gender string M


You said you are:
Female
Why am I getting this result when the user input is M and the gender string returns as M?


I appreciate any help the forum can provide.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is here:

Don't use == to compare strings. Use equals() instead:

The == operator checks if two expressions refer to the exact same object. It does not compare the content of objects. Even if you have two separate String objects with the same content, comparing them with == will return false because they are two separate objects.
 
Dwaine McMaugh
Greenhorn
Posts: 4
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Jesper.
A very rookie mistake and one I should have learned from prior experience.
I can now keep working on my project in prompt time. Thanks again.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic