Java - 在字符输入上使用三元运算符来获取布尔值



希望在 C# 中做一些事情:

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

但在爪哇

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

以上是我到目前为止尝试过的。想知道这是否可能。

编辑:我刚刚注意到.nextChar()不存在。编辑了片段以反映这一点。

"nextChar":假设in是一个Scanner,你的问题是扫描仪没有nextChar()方法。你可以读一整个单词,然后取它的第一个字符:

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

布尔值与三元组:如果你的输出是真/假,那么你不需要 if。你可以写:

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

布尔值与布尔值:另请注意,boolean是Java中的原始布尔类型。使用Boolean将强制将其包装为布尔类。

区分大小写:如果要允许"y"或"Y",请先强制输入已知大小写。由于charAt()返回原始字符,因此需要使用静态Character.toUpperCase()

溶液:

boolean isY = Character.toUpperCase(in.next().charAt(0)) == 'Y'
// - OR - 
boolean isY = in.next().startsWith("Y") // not case-insensitive
Boolean international_F = "Y".equals(in.next()); // next  returns a string
Boolean international_F =in.next().charAt(0) == 'Y';

你不需要三元运算符来简单地分配条件评估的结果(true/false(。如果您想根据条件评估的结果做某事,则需要一个三元运算符,例如

import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
System.out.print("Do you want to continue? [Y/N]: ");
boolean yes = in.nextLine().toUpperCase().charAt(0) == 'Y';
if (yes) {
System.out.println("You have chosen to continue");
} else {
System.out.println("You have chosen to stop");
}
// Or simply
System.out.print("Do you want to continue? [Y/N]: ");
if (in.nextLine().toUpperCase().charAt(0) == 'Y') {
System.out.println("You have chosen to continue");
} else {
System.out.println("You have chosen to stop");
}
// You can use ternary operator if you want to do something based on the result
// of evaluation of the condition e.g.
System.out.print("Do you want to continue? [Y/N]: ");
String response = in.nextLine().toUpperCase().charAt(0) == 'Y' ? "Yes" : "No";
System.out.println(response);
// Without a ternary operator, you would write it as:
System.out.print("Do you want to continue? [Y/N]: ");
String res;
char ch = in.nextLine().toUpperCase().charAt(0);
if (ch == 'Y') {
res = "Yes";
} else {
res = "No";
}
System.out.println(res);
}
}

运行示例:

Do you want to continue? [Y/N]: y
You have chosen to continue
Do you want to continue? [Y/N]: n
You have chosen to stop
Do you want to continue? [Y/N]: y
Yes
Do you want to continue? [Y/N]: n
No

这是一个演示您想要执行的操作的示例:

char a = 'a';
char b = 'b';
Boolean b1 = (a == 'a') ? true : false;
Boolean b2 = (a == b) ? true : false;
System.out.println(b1);
System.out.println(b2);

输出将是:

true
false

最新更新