+ 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.
3 odpowiedzi
+ 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
+ 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"
+ 1
Thanks! I understand now.