Gui
Gui

Reputation: 41

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...

Upvotes: -4

Views: 3234

Answers (3)

Stefaan Neyts
Stefaan Neyts

Reputation: 2067

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

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

Upvotes: 0

flogy
flogy

Reputation: 937

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

Upvotes: 3

Marco
Marco

Reputation: 726

The problem is that you're using a function pyramidVolume that basically returns nothing. This should work:

import java.util.Scanner;

public class CalcPyramidVolume {


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

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).toString());
  return;
}
}

Upvotes: 1

Related Questions