【问题标题】:Java method definitionJava 方法定义
【发布时间】:2015-03-21 21:10:06
【问题描述】:

我的代码是这样的:

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

【问题讨论】:

  • 用户名“Gui”怎么到现在都没有被占用?
  • @Carcigenicate 用户名是 StackOverflow 上的 not unique
  • @Jesper 哇哦,我以前从未注意到这一点。自从我加入以来已经有一年了,这有点令人难过:/

标签: java method-declaration


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    问题是您使用的函数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;
    }
    }
    

    【讨论】:

      【解决方案3】:
      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));
          }
      }
      

      【讨论】:

      • 请详细说明您的代码,解释它的作用以及解决问题的原因
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-07
      • 2023-01-19
      • 2015-12-14
      • 1970-01-01
      • 2014-05-16
      相关资源
      最近更新 更多