字节颜色
必须保留颜色(如红色或绿色)。
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/