user6527926
user6527926

Reputation: 55

How to convert a char to a boolean in Java?

I would like to display on the screen a question with two options (Are you married: y/n). The user would have to press or "y" or "n". After that I would like to print on the screen "married" or "not-married".

I've thought in using a char to get the input thorough the Scanner class (System.in) and after cast this char to a boolean type in order to display two options with an if statement. The problem is that I don´t know how to cast this char to a boolean type. Does it make sense? Is there other way to do this example in a different way?

Many thanks

Upvotes: 2

Views: 32059

Answers (5)

Edwin
Edwin

Reputation: 43

You can't cast a character into a boolean value, because how should the program know that 'y' means true and 'n' means false? Use an if statement

bool married = false;
if(input.equalsIgnoreCase("y"))
    married = true;

I bet a simple google search would have helped you with your homework.

Upvotes: 0

fabian
fabian

Reputation: 82461

You cannot simply cast char to boolean, but you can compare it to 'y' and 'n'

public static boolean charToBool(char c) {
    // c = Character.toLowerCase(c);
    switch (c) {
        case 'y':
            return true;
        case 'n':
            return false;
        default:
            throw new IllegalArgumentException("Must be either 'y' or 'n'.");
    }
}

Upvotes: 0

duffymo
duffymo

Reputation: 308753

I think an enum would be a good way to go. Encapsulate the rules inside your objects.

Binding user responses to objects is a view responsibility. Is the input a dropdown or text box?

Marital status is an interesting one. There are more flavors than "yes/no": single, married, divorced, separated, Kardashian, etc.

public class MaritalStatus {
    MARRIED, NOT_MARRIED;
}

Upvotes: 1

hyde
hyde

Reputation: 62787

Very simple:

boolean isYes = (inputChar=='y' || inputChar=='Y');

You could also convert the char to upper/lower case so you would not need ||. Depends on how many tests you have, if it's worth it.

And those parenthesis are not really needed in this case, as || has a higher precedence than assignment, but I personally find it clearer when "condition" like that is enclosed in parenthesis.

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

Yes, the way you trying to do is doesn't make scenes. You can do as following

Scanner sc=new Scanner(System.in);
String st=sc.nextLine();
if("y".equalsIgnoreCase(st)){
  // married
}else if("n".equalsIgnoreCase(st)){
 // not married
}

Upvotes: 2

Related Questions