javadrjava

Having Issues With Arguments and Parameters In Methods


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);


     }
   }

Solution

  • 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;
    }