Why aren’t you entering this if/Else?

Asked

Viewed 218 times

1

I run this code and the if/else if are not entering. What can be?

import java.util.Scanner;

public class VerificaLetra {

    public static void main(String[] args) {
    
        String sexo = " ";
        String letra;
        Scanner scan;
    
        System.out.print("Informe o sexo. F para feminino e M "+
                     "para Masculino: ");
        scan = new Scanner(System.in);
        letra = scan.nextLine();
    
        if (letra == "f" || letra == "F") {
            sexo = "Sexo = Feminino";
        }
        else if (letra == "m" || letra == "M") {
            sexo = "Sexo = Masculino";
        }
        System.out.println(sexo);        
    }
}
  • 1

    It’s because strings are objects, you need to use letra.equals("m"). There are several questions here about that, I marked yours as a duplicate of one of them.

  • Thanks! I’m new to the site, but I’ll try to search before the next one. I will test your answer, the topic you sent also has some cool answers!

  • It worked. I read the topic and managed to understand the concept well. Thank you!

1 answer

1


In Java String is a normal class and as the language has no operator overhead, can only make the comparison with the method equals().

import java.util.Scanner;

class VerificaLetra {
    public static void main(String[] args) {
        System.out.print("Informe o sexo. F para feminino e M para Masculino: ");
        Scanner scan = new Scanner(System.in);
        String letra = scan.nextLine();
        String sexo = " ";
        if (letra.equals("f") || letra.equals("F")) sexo = "Sexo = Feminino";
        else if (letra.equals("m") || letra.equals("f")) sexo = "Sexo = Masculino";
        System.out.println(sexo);        
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

You could use the equalsIgnoreCase() and make only one comparison in each if.

  • Thanks for the answer! I didn’t know this equalsIgnoreCase() will be very useful to me!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.