Why are not you entering this if / else? [duplicate]

1

I run this code and if / else if are not entering. What can it 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);        
    }
}
    
asked by anonymous 28.02.2017 / 17:34

1 answer

1

In Java String is a normal class and since the language has no operator overhead, it can only compare with the 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);        
    }
}

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

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

    
28.02.2017 / 17:51