How to convert a char to a boolean in Java?
Solution 1
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
}
Solution 2
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;
}
user6527926
Updated on September 27, 2020Comments
-
user6527926 over 3 years
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