java—将整数转换为打印字符串的最佳方法

biswetbf  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(363)

我有一个很小很可能很愚蠢的问题。我不知道该怎么走。我想弄清楚如何转换一个整数,以便像下面的单元测试那样打印出一个字符串。我不允许使用枚举,因为确切的问题要求它表示为整数。我需要hashmap,还是只需要简单的switch语句?当我运行单元测试时,我需要它打印出来:

Cat (Ragdoll: House Cat) is 1 year old, is 30 units fast.

但目前正在打印:

Cat (Ragdoll: 3) is 1 year old, is 30 units fast.

cat类(我删除了不相关的方法):

public class Cat extends Animal { 

    private Integer type;
    private String breed;

    static final Integer LION = 1;
    static final Integer TIGER = 2;
    static final Integer HOUSE_CAT = 3;
    static final Integer PUMA = 4;

    public Cat(int age, int speed, Integer type, String breed){
        super(age, speed);
        this.type = type;
        this.breed = breed;
    }

    public String getBreed() {
        return breed;
    }

    public Integer getType() {
        return type;
    }

    public String toString() {
        return ("Cat (" + breed + ": " + type + ")" + super.toString());

    }

}

单元测试(可以在dog类中使用枚举,因此没有问题)。

@Test
    void testAllParts() {
        Animal dog = new Dog(12, 30, Dog.type.GUNDOG, "Irish Setter");
        Animal cat = new Cat(1, 30, Cat.HOUSE_CAT, "Ragdoll");

        assertTrue(dog.isOlder(cat));
        assertFalse(cat.isOlder(dog));

        assertFalse(dog.isFaster(cat));
        assertFalse(cat.isFaster(dog));

        assertEquals("Dog (Irish Setter: GUNDOG) is 12 years old, is 30 units fast.", dog.toString());
        assertEquals("Cat (Ragdoll: House Cat) is 1 year old, is 30 units fast.", cat.toString());

        assertFalse(dog.equals(cat));

        Animal [] a = dog.multiply(2);
        assertEquals(a[0], a[1]);
        assertFalse(dog.equals(a[0]));
        assertEquals(2, a.length);

        a = cat.multiply(2);
        assertEquals(a[0], a[1]);
        assertFalse(cat.equals(a[0]));
        assertEquals(2, a.length);

    }
xtupzzrd

xtupzzrd1#

使用 enum 这是一个明显的选择,但既然你说你不能用它们,你可以用 Map 从值到名称:

private static final Map<Integer, String> TYPES = 
    Map.of(1, "Lion",
           2, "Tiger",
           3, "House cat",
           4, "Puma");

然后把它用在 toString 方法:

public String toString() {
    return ("Cat (" + breed + ": " + TYPES.get(type) + ")" + super.toString());
}

相关问题