将语句和String转换为byte

时间:2012-12-02 23:52:36

标签: java class byte switch-statement

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 个答案:

答案 0 :(得分:3)

交换机不是一个好的选择,因为在每种情况下你都需要一个break,这使得很多代码可以做的很少:

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

此外,拥有如此多的行意味着更多的bug存在空间。 但更糟糕的是,您实际上是使用代码来存储数据。

更好的选择是使用Map并查找String:

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

然后在你的方法中

return map.get(color);

答案 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"