Java方法定义

时间:2015-03-21 21:10:07

标签: java method-declaration

我的代码就像:

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类型中完成。我只是不明白为什么......

3 个答案:

答案 0 :(得分:3)

void 方法不会返回主方法中可以附加到该String的任何内容。您需要使方法返回 double ,然后返回变量 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

答案 1 :(得分:1)

问题在于您使用的函数pyramidVolume基本上不返回任何内容。这应该有效:

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

答案 2 :(得分:0)

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