枚举数组为带null的字符串

vu8f3i0k  于 2021-07-06  发布在  Java
关注(0)|答案(3)|浏览(304)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

上个月关门了。
改进这个问题
枚举文件如下所示。

package Tic;

public enum Player {
    X,O;

    @Override
    public String toString() {
        switch (this) {
            case X: return "X";
            case O: return "O";
            default: return "_";
        }
    }
}

我有一个要打印的枚举数组,如下所示:返回电路板的字符串表示形式。例如:“o\ux\no x\un\un”(null变为“\”)有没有一个简单的方法?

zwghvu4y

zwghvu4y1#

使用返回内置 .name() 方法获取枚举示例的字符串版本,如果为null,则使用下划线:

public enum Player {
    X, O;
    public static String asString(Player player) {
        return player == null ? "_" : player.name();
    }
}

要将播放器数组转换为字符串:

Player[] row = ...;
String rowAsString = Arrays.stream(row).map(Player::asString).collect(joining(""));
wb1gzix0

wb1gzix02#

最好使用枚举值来代替null,因为这样可以避免在获取字符串名称等效项时可能出现的nullpointerexception。您可以将显示名称传递给@查利阿姆斯壮示例的构造函数,或者这个简单的toStrug()重写确保空白值打印正确的显示值。 player.toString() :

public enum Player {
    X, O, BLANK;

    public String toString() {
        return this == BLANK ? "_" : this.name();
    }
}
public static void main(String[] args)
{
    Player[] row = { Player.O, Player.BLANK, Player.X};
    for (Player p : row) {
        System.out.print(p.toString());
    }
}
y4ekin9u

y4ekin9u3#

好的,首先让我们重写一下枚举。您正在使用示例方法将枚举转换为字符串,但在您的示例中,这实际上没有多大意义,因为您不能对空引用调用方法。您需要的是一个静态方法,它确定参数是否为null,并返回适当的字符串。见下表:

public enum Player {
    // Declaring the strings here, which seems clearer than a switch statement:
    X("X"),
    O("O");

    private final String str;

    private Player(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return str;
    }

    // This is a static method, so you can pass null references here
    public static String toString(Player player) {
        if (player == null) {
            return "_";
        }

        // Here we can call the instance method, because we know player is not null
        return player.toString();
    }
}

这样,我们就可以编写一些相当简单的驱动程序代码来实现您所描述的:

// This just sets up the array exactly like you described in the question:
Player[][] players = new Player[][] {
    {
        Player.O, null, Player.X
    },
    {
        Player.O, Player.X, null
    },
    {
        null, null, null
    }
};

// Loop through the outer array:
for (Player[] arr : players) {
    // For each outer array, we loop through the inner array:
    for (Player p : arr) {
        // For each Player in the inner array, we call our static toString() method and print the result:
        System.out.print(Player.toString(p));
    }

    //At the end of each inner array, we want to print a line terminator to separate them:
    System.out.println();
}

输出为:

O_X
OX_
___

相关问题