java - Switch 语句和字符串到字节

标签 java class byte switch-statement

字节颜色必须保留颜色(如红色或绿色)。 show() 方法的结果必须使用 switch 来分类和描述这种颜色(不同的变体,如:红-蓝,绿-红等)*不能使用枚举

public class Candy {

    //fields
    int quantity;
    byte color;
    double price;

    //constructor
    Candy(int quantity, byte color, double price)
    {
        this.quantity = quantity;
        this.color = color;
        this.price = price;
    }

    //this method have to show class fields
        public void show(String colors) 
    {
        switch(color)
        {
        case 1: colors = "red";
        case 2: colors = "green";
        case 3: colors = "blue";
    }

            //tried to convert 
    //String red = "Red";
    //byte[] red1 = red.getBytes();
    //String green = "Green";
    //byte[] green1 =  green.getBytes();



    public static void main(String[] args)
    {
    //program   
    }
}

我的路还好吗?如何将字符串保存为字节?谢谢

最佳答案

开关不是一个好的选择,因为在每种情况下都需要中断,这使得很多代码只做很少的事情:

switch (color) {
   case 1: colors = "red"; break;
   ... etc

此外,如此多的行意味着错误的范围更大。 但更糟糕的是,您本质上是在使用代码来存储数据。

更好的选择是使用映射并查找字符串:

private static Map<Byte, String> map = new HashMap<Byte, String>() {{
    put(1, "red");
    put(2, "green");
    etc
}};

然后在你的方法中简单

return map.get(color);

关于java - Switch 语句和字符串到字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13675330/

相关文章:

typescript 类 : How to initialize variables that require multiple promises?

java - Eclipse 不编译 java 文件(已经尝试了可能重复的答案)

python - 当类中的函数返回一个值时,它返回到哪里?

C# - 位和字节

java - 您可以使用 Retrofit 2 和 Gson 将 ISO 8601 时间戳直接映射到 OffsetDateTime 或 ZonedDateTime 吗?

java - 将数据从 BufferedReader 写入文件?

java - 如何创建一个对象来启动一个与我的程序一起运行的线程?

java - Android Studio 找不到 Oboe header ,但应用程序仍然运行

.net - 如何在 .NET 中将自定义类型保存为二进制数据?

java - 两个字节相乘