*
The moose likes Beginning Java and the fly likes Testing a string from a scanner input in an if/else statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Testing a string from a scanner input in an if/else statement" Watch "Testing a string from a scanner input in an if/else statement" New topic
Author

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

Dwaine McMaugh
Greenhorn

Joined: Aug 31, 2011
Posts: 4

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

Joined: Aug 16, 2005
Posts: 14074
    
  16

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Dwaine McMaugh
Greenhorn

Joined: Aug 31, 2011
Posts: 4

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Testing a string from a scanner input in an if/else statement
 
Similar Threads
While loops
IF condition in Struts 2.1.6
How to do a preview page for submitted form
Passing count
need help with endless loop when dealing with "if (keyboard.hasNextDouble())"