Click here to Skip to main content
15,867,756 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi! Can anyone tell me what is wrong with this java program?? it always executes the second condition (else) and doesn t recognize the first?
Thanks a lot.

What I have tried:

Java
import java.util.Scanner; 
public class Main 
{ 
public static void main(String[] args) 
{ 
System.out.println("Choose your gender:"); 
Scanner sc=new Scanner(System.in); 
String gender=sc.nextLine(); 
if(gender=="female") 
{System.out.println("Hi"); 
} 
else{ 
System.out.println("sorry"); 
} 

} 
}
Posted
Updated 29-Aug-17 18:25pm
v2
Comments
CPallini 29-Aug-17 17:13pm    
Java is just a bit nitpick in object comparison... :-)

Don't use == here: use gender.equals("female") rather than gender == "female"

Read the reason here: Java String.equals versus == - Stack Overflow[^] or here: How do I compare strings in Java? - Stack Overflow[^]
 
Share this answer
 
v2
Comments
CPallini 29-Aug-17 17:12pm    
5.
Member 13384372 30-Aug-17 12:32pm    
Great!I solved it!!
Member 13384372 30-Aug-17 12:37pm    
Do you also know how to write Exit function??
E.g:if the user enters "exit" at any point,it exists!
how would you edit the code above??
Thomas Daniels 30-Aug-17 13:04pm    
System.exit(0) exits the application.
Member 13384372 31-Aug-17 6:15am    
Yes I know this function but I don't know how to use it in the coditions??
I wrote it at the end and when I wrote something it just exited!!the thing I want is like to write "Exit"and it obeys and will exit at any point!!
Just a wild ass guess, but I'd say that gender == "female" condition never resolves to true.

You might want to find out what the contents of gender is when you expect the condition to be true.
 
Share this answer
 
Comments
CPallini 29-Aug-17 17:12pm    
5.
Advice: There is a common practice to help check user inputs.
That practice is to convert user inputs to lowercase or uppercase. This way, inputs like 'female', 'Female' or 'FEMALE' will all match the test.
 
Share this answer
 
Comments
Member 13384372 30-Aug-17 12:32pm    
Sorry but how?
Patrice T 30-Aug-17 12:36pm    
Google is your friend !
just try with keywords "Java lowercase"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900