+ 2

Help! It doesn't output anything (Java)

Hello. Could someone help me? I'm a beginner. This code doesn't output anything, and I can't find my mistake. import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner inGen=new Scanner (System.in); String gen=inGen.nextLine(); if(gen=="Hombre"){ System.out.print("Bienvenido."); } else if(gen=="Mujer"){ System.out.print("Bienvenida."); } } } I'll appreciate it.

7th Sep 2018, 4:46 PM
Stefan Aguilera
Stefan Aguilera - avatar
3 Antworten
+ 4
In Java, you should compare strings with .equals() instead of == also your input must match exactly, including capitals == is fine in most languages but Java handles Strings like other objects, and this compares the object reference. If it's not exactly the same String object then it won't return true
7th Sep 2018, 4:54 PM
Dan Walker
Dan Walker - avatar
+ 4
When you use "==" on Strings you are comparing their objects, gen is a different object from the compared ones. Try using equals() method. ex: gen = "Hombre"; if(gen.equals("Hombre")) { System.out.print(gen); } // prints "Hombre"
7th Sep 2018, 4:58 PM
Alexander Santos
Alexander Santos - avatar
+ 1
Thanks! I understand now.
7th Sep 2018, 6:17 PM
Stefan Aguilera
Stefan Aguilera - avatar