javamethod-declaration

Java method definition


My code is like:

import java.util.Scanner;

public class CalcPyramidVolume {


public static void pyramidVolume (double baseLength, double baseWidth, double pyramidHeight) {
  double volume;
  volume = baseLength * baseWidth * pyramidHeight * 1/3;
  return;
}

public static void main (String [] args) {
  System.out.println("Volume for 1.0, 1.0, 1.0 is: " + pyramidVolume(1.0, 1.0, 1.0));
  return;
}
}

And it said the print can't be done in the void type. I just don't understand why...


Solution

  • A void method does not return anything you could append to that String in the main method. You would need to make the method return a double and then return your variable volume:

    public static double pyramidVolume (double baseLength, double baseWidth, double pyramidHeight) {
      double volume;
      volume = baseLength * baseWidth * pyramidHeight * 1/3;
      return volume;
    }
    

    or shorter:

    public static double pyramidVolume (double baseLength, double baseWidth, double pyramidHeight) {
      return baseLength * baseWidth * pyramidHeight * 1/3;
    }
    

    Also see: http://en.wikibooks.org/wiki/Java_Programming/Keywords/void