【问题标题】:Arguments won't get passed into object参数不会传递给对象
【发布时间】:2013-10-01 20:53:03
【问题描述】:
public class BottledWaterTester {
public static void main (String args[])
{
    BottledWaterCalculator tester = new BottledWaterCalculator("USA", 350000000, 190.0, 8.5, 12.0);


    System.out.println("The country is " + tester.getCountryName());
    System.out.println("The population is " + tester.getPopulation());
    System.out.println("The number of times the bottles circle the Equator is " + tester.getNumberCircled());
    System.out.println("The average length of a bottle is " + tester.getLength());
    System.out.println("The average volume of a bottle is " + tester.getVolume());
}

}

所以我上面有这段代码。但是当我运行它时,我得到了这个输出:

*运行:

国家为空

人口为0

瓶子绕赤道的圈数是0.0

瓶子的平均长度是0.0

一瓶的平均体积是0.0

构建成功(总时间:0 秒)*

为什么?我显然将值传递到我的测试器对象中。构造函数在这里定义:

public class BottledWaterCalculator {

//instance vars
private String countryName;
private int population;
private double numberCircled;
private double avgLength;
private double avgVolume;

//constructor
// note: constructor name must always be same as public class name, or else it's a method
public BottledWaterCalculator(String country, int pop, double number, double lengthAvg, double volumeAvg)
{
    country = countryName;
    pop = population;
    number = numberCircled;
    lengthAvg = avgLength;
    volumeAvg = avgVolume;
}

我真的是编程新手,所以我不明白发生了什么。

【问题讨论】:

  • 您需要执行this.countryName = country,因为作业的左侧(LHS)是设置为RHS的内容,依此类推。也可能在您的问题中标记 Java
  • 谢谢。有效。 Java非常细致。

标签: java parameters constructor arguments


【解决方案1】:

你需要在分配给构造函数时分配这个关键字。

【讨论】:

  • 欢迎来到 Stack Overflow!就目前而言,这个答案更适合作为评论。也许您可以通过添加提问者可以用来解决问题的演示代码来改进它?
【解决方案2】:

修改代码如下:

public class BottledWaterCalculator {

//instance vars
private String countryName;
private int population;
private double numberCircled;
private double avgLength;
private double avgVolume;

//constructor
// note: constructor name must always be same as public class name, or else it's a method
public BottledWaterCalculator(String country, int pop, double number, double lengthAvg, double volumeAvg)
{
    countryName = country;
    population = pop;
    numberCircled = number ;
    avgLength = lengthAvg ;
    avgVolume = volumeAvg ;
}

【讨论】:

    【解决方案3】:

    在你的构造函数中翻转变量赋值。例如:

    countryName = country;
    

    您当前正在设置要传递给局部变量值的内容。 (全部为空/null/未赋值)

    【讨论】:

      【解决方案4】:
      public BottledWaterCalculator(String country, int pop, double number, double lengthAvg, double volumeAvg)
      {
        countryName  = country ;
        population=  pop;
        numberCircled =  number ;
        avgLength = lengthAvg;
        avgVolume = volumeAvg ;
      }
      

      变量的顺序错误,你是在为构造函数参数赋值,而不是一个对象

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多