Problem with a data member(field) in Java and priting it out? how to properly implement?
I want to print out the result of calcWork() in printReport() but I keep getting 0.0 Is there a problem with setting work = this.totalWork;?
public class CarnotEngine {
public double n = 10;
public double R = 4;
public double Th = 8;
public double Tc =2;
public double Va = 4;
public double Vb = 3;
public double totalWork;
public double highTemp, lowTemp;
public double efficientcy;
public CarnotEngine(double highTemp, double lowTemp ){
this.highTemp = highTemp;
this.lowTemp = lowTemp;
}
public double calcWork(){
double Qh;
double work;
Qh = (n*R*highTemp)*log(Vb/Va);
work =(1-lowTemp/highTemp)*Qh;
work = this.totalWork;
return work;
}
public void printReport() {
System.out.println("开发者_开发百科Simulation Result for Carnot Engine");
System.out.println("work done" + totalWork );
public static void main(String[] args) {
CarnotEngine carengine = new CarnotEngine(500, 200);
carengine.calcWork();
carengine.calcEfficientcy();
carengine.printReport();
}
}
Your assignment is backwards:
work = this.totalWork;
should instead be
this.totalWork = work;
The way it is right now you're calculating everything in work
and immediately overwriting it with the value from this.totalWork
.
You should try to understand the difference between local variables (work) and member variables (totalWork) and their scope.
Others will probably beat me in correcting the problem, but it is important that if you learn an object oriented language like Java, that you need to understand these concepts very well.
I'm not sure exactly what you are trying to do. On the line where you set work=this.totalWork, this.totalWork is equal to 0.0, thus you are getting the result I would expect. Do you mean to set this.totalWork to the value of work rather than work to the value of totalWork?
As far as I can tell, totalWork
is never initialized and/or modified.
Default initialization value is 0.0, hence this is a value that you see in your printout
精彩评论