有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Switch语句和字符串到字节

byte color必须保持颜色(如红色或绿色)。 show()方法的结果必须使用开关来分类和描述这些颜色(在不同的变体中,如:红蓝、绿红等)*不能使用枚举

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   
    }
}

我走的好吗?如何将字符串保存在字节中?谢谢


共 (2) 个答案

  1. # 1 楼答案

    在一个byte中,您可以存储8种可能的组合。 在我的决定中,我声明第一个位置(字节的二进制表示)是“蓝色”,第二个是“绿色”,第三个是“红色”。这意味着如果我们有001-它是蓝色的。如果101——它的红蓝颜色等等。 这是您的show()方法:

    public void show() 
    {
        switch (color & 4){
            case 4:
                System.out.print("red ");
            default:
                switch (color & 2){
                    case 2:
                        System.out.print("green ");
                    default:
                        switch (color & 1){
                            case 1:
                                System.out.print("blue");
                        }
                }
        }
        System.out.println();
    }
    

    调用方法:

    new Candy(1, (byte)7, 10d).show(); //prints "red green blue"
    
  2. # 2 楼答案

    开关不是一个好的选择,因为您在任何情况下都需要一个break,这使得很多代码很少执行:

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

    而且,有这么多行意味着有更多的bug空间。 但更糟糕的是,您实际上是在使用代码来存储数据

    更好的选择是使用地图并查找字符串:

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

    那么在你的方法中

    return map.get(color);