Java 胜诉';不要传递到对象中
} 我有上面的代码。但当我运行它时,我得到以下输出: *运行: 国家是无效的 人口为0 瓶子绕赤道的圈数为0.0 瓶子的平均长度是0.0 瓶子的平均体积是0.0 生成成功(总时间:0秒)* 为什么??很明显,我正在将值传递到我的tester对象中。此处定义了构造函数:Java 胜诉';不要传递到对象中,java,parameters,constructor,arguments,Java,Parameters,Constructor,Arguments,} 我有上面的代码。但当我运行它时,我得到以下输出: *运行: 国家是无效的 人口为0 瓶子绕赤道的圈数为0.0 瓶子的平均长度是0.0 瓶子的平均体积是0.0 生成成功(总时间:0秒)* 为什么??很明显,我正在将值传递到我的tester对象中。此处定义了构造函数: public class BottledWaterTester { public static void main (String args[]) { BottledWaterCalculator tester = new
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());
}
我对编程真的很陌生,所以我不明白发生了什么
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;
}
变量顺序错误,您将值分配给构造函数参数,而不是一个对象
变量顺序错误,将值分配给构造函数参数,而不是构造函数翻转变量分配中的对象。例:
public BottledWaterCalculator(String country, int pop, double number, double lengthAvg, double volumeAvg)
{
countryName = country ;
population= pop;
numberCircled = number ;
avgLength = lengthAvg;
avgVolume = volumeAvg ;
}
您当前正在设置传递给局部变量值的内容。(全部为空/空/未赋值)在构造函数翻转变量赋值中。例:
public BottledWaterCalculator(String country, int pop, double number, double lengthAvg, double volumeAvg)
{
countryName = country ;
population= pop;
numberCircled = number ;
avgLength = lengthAvg;
avgVolume = volumeAvg ;
}
您当前正在设置传递给局部变量值的内容。(全部为空/空/未分配)更改代码如下:
countryName = country;
更改代码如下:
countryName = country;
您需要在分配给构造函数时分配此关键字。您需要在分配给构造函数时分配此关键字。您需要执行
this.countryName=country
,因为分配的左侧(LHS)是设置为RHS的,依此类推。可能在您的问题中标记Java。成功了。Java非常细致。您需要执行this.countryName=country
,因为赋值的左侧(LHS)是设置为RHS的,以此类推。可能在您的问题中标记Java。成功了。Java非常细致。欢迎来到Stack Overflow!目前来看,这个答案更适合作为评论。也许您可以通过添加提问者可以用来解决问题的演示代码来改进它?欢迎使用堆栈溢出!目前来看,这个答案更适合作为评论。也许您可以通过添加提问者可以用来解决问题的演示代码来改进它?