0

[JAVA] Easiest way to take ‘Y’ or ‘N’ as scanner inputs for boolean ?

Hi. I have a boolean scanner I’d like to take input as ‘Y’ for true and ‘N’ for false. Whats the best way to do this?

12th Aug 2019, 8:04 AM
Raj Grewal
Raj Grewal - avatar
6 Antworten
+ 4
//Here you go, it accepts upper and lower case character of Y theres no need for N because if no Y it's always N 👍 https://code.sololearn.com/c9JUpuU2dlek/?ref=app
12th Aug 2019, 9:51 AM
D_Stark
D_Stark - avatar
+ 4
What behaviour should your program exhibit if the input is neither Y nor N?
12th Aug 2019, 8:58 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
thanks bro D_Stark :)
12th Aug 2019, 11:52 AM
Raj Grewal
Raj Grewal - avatar
0
I say take the input as char, then use a simple switch case to return a Boolean
12th Aug 2019, 8:20 AM
Trigger
Trigger - avatar
0
unfortunately I can only use a predefined boolean attribute. Would it still work?
12th Aug 2019, 8:37 AM
Raj Grewal
Raj Grewal - avatar
0
You cant input "Y" and expect the scanner to store true and assign it to as a boolean you need some conditional statements. //I think this will work let me test it my self as I just wrote it... Boolean sc = new Scanner(System.in).nextLine().equals("Y")?true:false;
12th Aug 2019, 9:37 AM
D_Stark
D_Stark - avatar