2012-12-02 71 views
2

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

我是在好辦法嗎?如何保持字符串的字符串?由於

+0

你的意思是編碼一個字節的這三種顏色的所有可能的組合? – bellum

+0

你的問題是什麼? –

+0

@bellum該字節(顏色)的每一位都必須存儲一種顏色。 – Fastkowy

回答

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" 
+0

有必要使用switch語句:/有什麼辦法可以在不使用StringBuilder的情況下做到這一點?不管怎樣,謝謝 ! – Fastkowy

+0

答覆已更新。史詩功課:) – bellum

+0

這就像你propably知道......老師嘿;)謝謝! – Fastkowy

3

交換機是不是一個好的選擇,因爲你需要一個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);