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

Java - Use ternary operator on char input to get boolean

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

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

但在Java

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

以上是我目前尝试过的方法。想知道这是否可能。

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

这是一个演示您想要做什么的示例:

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

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

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

boolean 与 ternery: 如果你的输出是 true/false,那么你不需要 if。你可以只写:

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

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

区分大小写:如果要允许'y'或'Y',首先强制输入已知大小写。由于 charAt() returns 原始字符,您需要使用静态 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