转换为switch语句

问题描述 投票:0回答:1

如何将其转换为 switch 语句?我已经尝试过几次了。我不确定我错过了什么。

double totalPrice = 0.0;
if (venue.equals("Rod Laver")) {
    totalPrice = 225.25 * numOfTickets;
} else if (venue.equals("Margaret Court")) {
    totalPrice = 177.75 * numOfTickets;
} else if (venue.equals("John Cain")) {
    totalPrice = 145.50 * numOfTickets;
} else {
    System.out.println("Invalid venue entered");
     // Exit program if venue is invalid
}

// Display the total price to the user
System.out.printf("\nHave a wonderful day at the %s venue.\n\n", venue);
System.out.printf("Your total price is $%.2f.\n\n", totalPrice);

我尝试过这个,但没有成功。我显然错过了一些东西。我对 Java 还是很陌生。有人可以帮忙吗?

switch (venue) {
    case venue:
    System.out.println("Rod Laver");
    totalPrice = 225.25 * numOfTickets;
    break;

    case 2:
    System.out.println("Margaret Court");
    totalPrice = 177.75 * numOfTickets;
    break;

    case 3:
    System.out.println("John Cain");
    totalPrice = 145.50 * numOfTickets;
    break;

    default:
    System.out.println("Invalid venue entered");
    break;
}

// Display the total price to the user
System.out.printf("\nHave a wonderful day at the %s venue.\n\n", venue);
System.out.printf("Your total price is $%.2f.\n\n", totalPrice);
java switch-statement
1个回答
0
投票

您可以像这样进行切换:

double totalPrice = 0.0;
    switch(venue) {
        case "Rod Laver":
            totalPrice = 225.25 * numOfTickets;
            break;
        case "Margaret Court":
            totalPrice = 177.75 * numOfTickets;
            break;
        case "John Cain":
            totalPrice = 145.50 * numOfTickets;
            break;
        default:
            System.out.println("Invalid venue entered");
            break;
    }
© www.soinside.com 2019 - 2024. All rights reserved.