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

我对编程真的很陌生,所以我不明白发生了什么。

4

4 回答 4

1
public BottledWaterCalculator(String country, int pop, double number, double lengthAvg, double volumeAvg)
{
  countryName  = country ;
  population=  pop;
  numberCircled =  number ;
  avgLength = lengthAvg;
  avgVolume = volumeAvg ;
}

变量的顺序错误,您正在为构造函数参数分配值,而不是对象之一

于 2013-09-26T03:42:27.070 回答
0

在您的构造函数中翻转变量赋值。前任:

countryName = country;

您当前设置传递给局部变量值的内容。(这些都是空的/空的/未分配的)

于 2013-09-26T03:43:30.557 回答
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)
{
    countryName = country;
    population = pop;
    numberCircled = number ;
    avgLength = lengthAvg ;
    avgVolume = volumeAvg ;
}
于 2013-09-26T03:46:09.507 回答
0

您需要在分配给构造函数时分配此关键字。

于 2013-09-26T04:38:40.920 回答