timNorth timNorth - 4 months ago 8
Java Question

Getting a null output with code

In the following code I have used constructors and accessors method to compute the volume in litres that a pool can hold.

public class exampleproblem {
final static double PI = 3.14;
private String num;
private double height;
private String height1;
private double r1;
private double r2;
public exampleproblem(String num1){
num = num1;
}
public void setHeight(double h){
height=h;
}
public void setR1(double rr){
r1 = rr;
}
public void setR2(double rrr){
r2 = rrr;
}
public String getNum(){
return num;
}
public String getHeight1(){
return height1;
}
public double getPoolCost(){
return ((PI*height/3)*(r1*r1+r2*r2+r1*r2))/1000;
}
public static void main( String[] args ) {
exampleproblem pool1 = new exampleproblem("1.0");
exampleproblem pool2 = new exampleproblem("2.0");
exampleproblem height1 = new exampleproblem("20.0");
pool1.setHeight(20.0);
pool1.setR1(3.0);
pool1.setR2(5.0);
System.out.println("Container Num: " + pool1.getNum());
System.out.println("H: " + height1.getHeight1());
System.out.println("Litres: " + pool1.getPoolCost());
}
}


With this code I am getting the following output:

Container Num: 1.0
H: null
Litres: 1.0257333333333334


when I should be getting:

Container Num: 1.0
H: 20.0
Litres: 1.0257333333333334


not quite sure how to fix this output line

H: null

Answer

Change your method

from

public void setHeight(double h){
    height=h;
} 

to

public void setHeight(double h){
    height=h;
    height1 = Double.toString(h);
}