如何在java中使用switch case来区分字符?

时间:2016-09-21 06:00:22

标签: java

我想用字母代替数字而不是数字。所以它将是免费停车R,有盖停车C和车库停车G。我试图将它转换为if语句,但似乎无法弄清楚如何让它工作任何帮助将不胜感激。

    /*get users parking choice*/
    System.out.println("What kind of parking would you like press 1 for free parking, " +
            " 2 for a Covered parking, or 3 for garage parking" );
    parking = garageType.nextInt();

    switch (parking){
        case 1:
            type = "free";
            gPrice = 0;
            break;
        case 2:
            type = "covered";
            gPrice = 3000;
            break;
        case 3:
            type = "garage";
            gPrice = 6000;
            break;
        default:
            System.out.println("That was an invalid option please try again");
            break;
    }
    /* get total price*/
    total = condoPrice+gPrice;
    /*show the user their choices and condo, parking and total price*/
    System.out.println("You have selected a condo with a view of the "
            + view + " for $" + condoPrice + " with " + type + " parking, " +
            " your total for this condo and parking is $ " + total);
}

2 个答案:

答案 0 :(得分:4)

     System.out.println("What kind of parking would you like press 'R' for free parking, " +
            " 'C' for a Covered parking, or 'G' for garage parking" );
    parking = garageType.nextChar();

    switch (parking){
        case 'R':
            type = "free";
            gPrice = 0;
            break;
        case 'C':
            type = "covered";
            gPrice = 3000;
            break;
        case 'G':
            type = "garage";
            gPrice = 6000;
            break;
        default:
            System.out.println("That was an invalid option please try again");
            break;
    }
    /* get total price*/
    total = condoPrice+gPrice;
    /*show the user their choices and condo, parking and total price*/
    System.out.println("You have selected a condo with a view of the "
            + view + " for $" + condoPrice + " with " + type + " parking, " +
            " your total for this condo and parking is $ " + total);
}

答案 1 :(得分:0)

要将字符用作决策参数,您需要将字符作为用户的输入。

目前您正在将整数作为输入

nextChar()

你可以使用这个功能来阅读一个角色,然后通过将你的决定保持在一个单一的引用来比较它,比如R' R'

希望它有帮助!