Reputation: 193
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());
}
}
So I have this code above. But when I run it I get this output:
*run:
The country is null
The population is 0
The number of times the bottles circle the Equator is 0.0
The average length of a bottle is 0.0
The average volume of a bottle is 0.0
BUILD SUCCESSFUL (total time: 0 seconds)*
WHY?? I'm clearly passing values into my tester object. The constructor is defined here:
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;
}
I'm really new to programming so I don't understand what's going on.
Upvotes: 1
Views: 114
Reputation: 485
Change the code as below:
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 ;
}
Upvotes: 0
Reputation: 5468
In your constructor flip variable assignment. Ex:
countryName = country;
Your currently setting what you are passing in to the local variable value. (Which are all empty / null / unassigned)
Upvotes: 0
Reputation: 2737
public BottledWaterCalculator(String country, int pop, double number, double lengthAvg, double volumeAvg)
{
countryName = country ;
population= pop;
numberCircled = number ;
avgLength = lengthAvg;
avgVolume = volumeAvg ;
}
wrong order of variables, you are assigning values to constructor parameters, not objects one
Upvotes: 1