如何在Switch情况下分配价格值?

时间:2019-03-29 10:34:22

标签: java switch-statement

使用Switch分配价格是否合适?如果可能的话,我该怎么办。我知道在切换情况下必须有一条语句,但是我不确定要分配值并获取值。

float one = 244.50f, two = 125.75f, three = 323.33f, four = 46.29f, five = 3323.65f, price; 
int choice, quantity, yn;

System.out.print("Please enter the assigned number of the item sold: "); 
choice = display.nextInt();

switch(choice){ 
        case 1:
            break;
        case 2:
            break; 
        case 3:
            break; 
        case 4:
            break; 
        case 5:
            break;

} // end of switch case

System.out.print("Please enter the quantity of the item sold: "); 
quantity = display.nextInt();

System.out.print("Price is: ");

我希望用户输入1时输出为244.50f,依此类推。

4 个答案:

答案 0 :(得分:4)

使用地图代替

 var map = Map.of(1, 244.50f, 2, 125.75f); // and like so you can fill the map
 var somefloat = map.get(1);
 // or you can use 
 var somefloat = map.getOrDefault(1, 0f);

示例在Java 10+中

答案 1 :(得分:3)

尽管这是一个答案,但它也是YCF_L的补充。

如果您不将Java 10与Map#of一起使用,则可以使用以下内容:

private float[] prices = {
        244.50f,
        125.75f,
        323.33f,
        46.29f,
        3323.65f
};

private float getPrice(int choice) {
    if (choice < 0 || choice >= prices.length) {
        throw new IllegalArgumentException("Invaid choice");
    }
    return prices[choice - 1];
}

答案 2 :(得分:3)

仅出于您的参考和教育目的。自上一个Java-12版本以来,开关表达式在preview language feature中可用。它可能看起来像:

float price = switch (choice) {
    case 1 -> 244.50f;
    case 2 -> 125.75f;
    case 3 -> 323.33f;
    case 4 -> 46.29f;
    case 5 -> 3323.65f;
    default -> 0;
};
System.out.println(price);

查看更多JEP 325: Switch Expressions (Preview)

答案 3 :(得分:-1)

public class test { 
    public static void main(String[] args) 
    { 
        int choice = 5; 

        float  price = 0; 
        switch (choice) { 
        case 1: 
            price = 244.50f; 
            break; 
        case 2: 
            price = 125.75f; 
            break; 
        case 3: 
            price = 323.33f; 
            break; 
        case 4: 
            price = 46.29f; 
            break; 
        case 5: 
            price = 3323.65f; 
            break; 
        default: 
            break; 
        } 
        System.out.println(price); 
    } 
} 
May be this one help you