0

I'm having difficulty with this certain bit of code in my most recent assignment. This assignment displays prices to the user for gas, asks what type they would like and how many gallons. The program returns the total price as a double. I've created a switch in the method calculatePrice that would return an answer. I'm having trouble gathering that information and somehow printing it to the method displayTotal. Also, displayTotal must be a double. Any help is kindly appreciated.

public static double calculatePrice(int type, double gallons){

       switch (type){

      case 1:
        System.out.printf("You owe: %.2f" , gallons * 2.19);
        break;
      case 2: 
        System.out.printf("You owe: %.2f",  gallons * 2.49);
        break;
      case 3:
        System.out.printf("You owe: %.2f", gallons * 2.71);
        break;
      case 4:
        System.out.printf("You owe: %.2f", gallons * 2.99);
       }
    return type; 

     }

    public static void displayTotal(double type){


      System.out.println(type);


     }
   }
Jusinr518
  • 33
  • 5

2 Answers2

1

Looks like a simple mistake - you're returning type from calculatePrice, not the calculated value:

return type;

What you want there is to calculate the result and return that result, not the type. Also if you want to print it first it helps to put it into a local variable. Example:

public static double calculatePrice(int type, double gallons) {
    double result = 0;
    switch (type) {
        case 1:
            result = gallons * 2.19;
        break;
        case 2:
            result = gallons * 2.49;
        break;
        case 3:
            result = gallons * 2.71;
        break;
        case 4:
            result = gallons * 2.99;
    }
    System.out.printf("You owe: %.2f", result);
    return result;
}
mvmn
  • 3,717
  • 27
  • 30
0

You need to preserve the result of multiplication of gallons and price/gallon in a variable and return it.

public static double calculatePrice(int type, double gallons){
    switch (type) {
        case 1:
            return gallons * 2.19;
        case 2: 
            return gallons * 2.49;
        case 3:
            return gallons * 2.71;
        case 4:
            return gallons * 2.99;
     } 
}

public static void displayTotal(double type, double gallons){
    double totalPrice = calculatePrice(type, gallons);
    System.out.printf("You owe: %.2f", totalPrice);
}
akshaynagpal
  • 2,965
  • 30
  • 32