如何将int值映射到String值

时间:2017-12-31 08:15:06

标签: java

如何能够将int值1,2和3映射到String,因此它会输出“Small(300)”,“Medium(600)”和“Large(1200)”?

public static int newPackageDeal(String msg, String error) 
{
    int packageDeal;   

    do 
    {   
        System.out.println(msg);                   
        packageDeal = in.nextInt();                   
    }
    while (packageDeal != 1 && packageDeal != 2 && packageDeal != 3);

    return packageDeal;
}

3 个答案:

答案 0 :(得分:2)

您可以使用switch声明:

String output;
switch (packageDeal) {
    case 1:
        output = "Small (300)";
        break;

    case 2:
        output = "Medium (600)";
        break;

    case 3:
        output = "Large (1200)";
        break;

    default:
        output = "NA";
}

如果程序中有较长期的需要将处理整数映射到字符串,则可以将这些关系存储在数据库表中,然后在Java代码中的某处填充映射。然后,您可以随时查找字符串描述。

答案 1 :(得分:1)

您可以使用HashMap将输出值与数字相对应。

HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(1,"Small (300)");
map.put(2,"Medium (600)");
map.put(3,"Large (1200)"); 

然后根据newPackageDeal()方法中的packageDeal返回输出值。

public static String newPackageDeal(String msg, String error) 
{
    int packageDeal; 

    do 
    {   
        System.out.println(msg);                   
        packageDeal = in.nextInt();                   
    }
    while (packageDeal != 1 && packageDeal != 2 && packageDeal != 3);

    return map.get(packageDeal);
}

答案 2 :(得分:1)

将您的交易放在地图中,按数字索引。

这比使用if/else switch个语句更加可扩展,您的while条件变得更加清晰。

public static String newPackageDeal(String msg, String error)
{
    Map<Integer, String> dealsByNumber = new HashMap<>();
    dealsByNumber.put(1, "Small (300)");
    dealsByNumber.put(2, "Medium (600)");
    dealsByNumber.put(3, "Large (1200)");
    // Easy to extend with other deals later on!

    Scanner in = new Scanner(System.in);

    int packageDeal;

    do
    {
        System.out.println(msg);
        packageDeal = in.nextInt();
    }
    while (!dealsByNumber.containsKey(packageDeal));

    return dealsByNumber.get(packageDeal);
}