-4

我的代码是这样的:

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类型中进行打印。我只是不明白为什么...

4

3 回答 3

3

void方法不会返回您可以在 main 方法中附加到该字符串的任何内容。您需要使该方法返回一个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

于 2015-03-21T21:14:08.450 回答
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;
}
}
于 2015-03-21T21:13:57.787 回答
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));
    }
}
于 2015-03-21T21:16:48.193 回答