Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return values found in a switch statement Java

How would I return the values that I found in this switch statement to the rest of the class for use (I want to use oneTotal, twoTotal, etc. out side of that switch statement)? Here is the code for the switch statement:

        switch(itemNo){
        case 1:
            double oneTotal = 2.98 * userQuantity;
            return oneTotal;
        case 2:
            double twoTotal = 4.50 * userQuantity;
            return twoTotal;
        case 3:
            double threeTotal = 9.98 * userQuantity;
            return threeTotal;
        case 4:
            double fourTotal = 4.49 * userQuantity;
            return fourTotal;
        case 5:
            double fiveTotal = 6.87 * userQuantity;
            return fiveTotal;
        }

Out side of the switch statement I want the fiveTotal's to be added up once the user's stops using the switch statement (I have it in a while loop), and then want the five totals to be returned to be used in the main method of the class (the switch statement is in its own double, non void class so it can return values).

like image 461
Fyree Avatar asked Dec 20 '22 06:12

Fyree


1 Answers

On Java 14, you can use

double total = switch(itemNo){
        case 1 -> 2.98 * userQuantity;
        case 2 -> 4.50 * userQuantity;
        case 3 -> 9.98 * userQuantity;
        case 4 -> 4.49 * userQuantity;
        case 5 -> 6.87 * userQuantity;
        };
like image 144
Guillaume F. Avatar answered Dec 21 '22 19:12

Guillaume F.