参数不会传递给对象

时间:2013-09-26 03:38:25

标签: java parameters constructor arguments

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秒)*

WHY ??我清楚地将值传递给我的测试对象。构造函数在这里定义:

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 个答案:

答案 0 :(得分:1)

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

变量的顺序错误,您要为构造函数参数赋值,而不是对象

答案 1 :(得分:0)

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

countryName = country;

您当前正在设置传入本地变量值的内容。 (这些都是空的/ null /未分配的)

答案 2 :(得分: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 ;
}

答案 3 :(得分:0)

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