Search code examples
javamethodsreturn

Method definition - Volume of a pyramid - Returning method call to another method


I can't figure out what's happening to cause the errors that I'm receiving to return the pyramidVolume that I'm trying to call. This problem comes from zyBooks and I can only edit the class CalcPyramidVolume. Here is my code

import java.util.Scanner;

public class CalcPyramidVolume {
   double calcPyramidVolume(double baseLength, double baseWidth, double baseHeight);
   double baseArea;
   double pyramidVolume;
   
   baseArea = baseLength * baseWidth;
   pyramidVolume = baseArea * baseHeight * (1.0/3.0);
   
   return pyramidVolume;

   public static void main (String [] args) {
      Scanner scnr = new Scanner(System.in);
      double userLength;
      double userWidth;
      double userHeight;

      userLength = scnr.nextDouble();
      userWidth = scnr.nextDouble();
      userHeight = scnr.nextDouble();

      System.out.println("Volume: " + pyramidVolume(userLength, userWidth, userHeight));
   }
}

So I'm trying to pass the arguments in the output statement to the parameters of the calcPyramidVolume method.
I get the following error messages from the compiler.

CalcPyramidVolume.java:8: error: <identifier> expected
   baseArea = baseLength * baseWidth;
           ^
CalcPyramidVolume.java:9: error: <identifier> expected
   pyramidVolume = baseArea * baseHeight * (1.0/3.0);
                ^
CalcPyramidVolume.java:11: error: illegal start of type
   return pyramidVolume;
   ^
CalcPyramidVolume.java:11: error: <identifier> expected
   return pyramidVolume;
                       ^
4 errors

I'm not sure what is meant by identifier expected, I've triple-checked the spelling and declarations of my variables.


Solution

  • Finally got it! I'm only able to change what's above the main() method. After reviewing my text material more thoroughly, I seen that I needed to add a public class static double pyramidVolume. I've listed my correction to only the updated class below, since the rest is the same.

    public class CalcPyramidVolume {
    
       public static double pyramidVolume(double userLength, double userWidth, double userHeight) {
       double baseArea;  //added public static class with same variables as in the main method
       
       baseArea = userLength * userWidth;
       double pyramidVolume = baseArea * userHeight * (1.0/3.0);  //added double type to pyramidVolume since it's not declared inside the braces
       
       return pyramidVolume;
       }