Java - Use ternary operator on char input to get boolean

Edward Suzuki :

Looking to do something like in C#:

bool walkable = t.Type == TileType.Green ? true : false;

but in Java

Boolean international_F = (in.next() == 'Y') ? true : false;

The above is what I've tried so far. Wondering if it's even possible.

EDIT: I just noticed .nextChar() doesn't exist. Edited snippet to reflect that.

AjahnCharles :

"nextChar": Assuming in is a Scanner, your issue is that Scanner doesn't have a nextChar() method. You could read a whole word, and then take it's first char:

char theChar = in.next().charAt(0)

boolean vs ternery: If your outputs are true/false, then you don't need an if. You can just write:

bool walkable = t.Type == TileType.Green; // C#
boolean international_F = in.next().charAt(0) == 'Y'` // Java

boolean vs Boolean: Please also note that boolean is the primitive boolean type in Java. Using Boolean will force it to be wrapped as the Boolean class.

case sensitivity: If you want to allow 'y' or 'Y', force the input to a known case first. Since charAt() returns primitive char, you need to use the static Character.toUpperCase().

Solution:

boolean isY = Character.toUpperCase(in.next().charAt(0)) == 'Y'
// - OR - 
boolean isY = in.next().startsWith("Y") // not case-insensitive

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=415857&siteId=1