Java 方法定义

Java method definition

我的代码是这样的:

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

而且说void类型打印不出来。我只是不明白为什么...

问题是您使用的函数 pyramidVolume 基本上 returns 什么都没有。这应该有效:

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

A​​ void 方法不会 return 您可以在 main 方法中附加到该字符串的任何内容。您需要将方法 return 设置为 double 然后 return 您的变量 volume:

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

或更短:

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

另见:http://en.wikibooks.org/wiki/Java_Programming/Keywords/void

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