About printing with printf a boolean in Java

0

I am learning how to program in Java and I am doing an exercise where I have to print on the screen with printf a Boolean variable. The variable in question is gender, which can be M or F.

Let's see the initialization of the variable:

boolean sex = true; // I set it to true because it gave me a Netbeans error and I did not know it was initialized, but I do not know how to set M to true and that F corresponds to false.

System.out.printf ("The value of the variable sex is% s% n", sex); // I think it would be fine that way, but I fail to guess that this will print true, but not M, that is what I want, because I do not know how to program what corresponds to true and what corresponds to false.

Thank you very much:)

    
asked by Sergio 04.03.2018 в 16:28
source

3 answers

2

A variable of type boolean can only be equal to true or false nothing more. To do what you want, you must support conditional or other mechanisms so that M is true and F is false or vice versa.

Example:

boolean sexoM = true;

        if (sexoM) {
            // Entra aquí solamente porque sexoM es true
            System.out.println("M");
        } else {
            System.out.println("F");
        }

At boolean you can not assign anything other than true or false .

Another way:

boolean sexoM = true;
boolean sexoF = false;

        if (sexoM) {
            System.out.println("Soy M");
        }

        if (sexoF) {
            // No entra aquí porque sexoF es false
            System.out.println("No soy F");
        }
    
answered by 04.03.2018 в 16:57
1

I think the easiest way to solve this would be with a Ternary Operator .

A Ternary Operator in its most basic form is presented as follows:

In summary, evaluate a Expresión booleana , if the same is true, it would take what we assigned before the two points : , and if it is false, it would take what we assign after the two points.

In this case the evaluation would be very simple, for example:

    statusSexo = (sexoM) ? "M" : "F";  

Here the variable statusSexo will acquire the value M if sexoM is true , otherwise, it will acquire the value F .

The program would then be like this:

    boolean sexoM = true;
    String statusSexo = (sexoM) ? "M" : "F";  
    System.out.println(statusSexo);

Here you will have on screen:

M

We do another test changing the value of the boolean variable to false :

    boolean sexoM = false;
    String statusSexo = (sexoM) ? "M" : "F";  
    System.out.println(statusSexo);

Here you will have a screen:

F
    
answered by 04.03.2018 в 17:30
0

Using a conditional you could do something like this:

if(sexo) {
    Char genero = 'M';
} else {
    Char genero = 'F';
}

Afterwards you can show the result of said conditional on the screen:

System.out.printf("%c %n", genero);
    
answered by 04.03.2018 в 16:44