英文:
Where did I messed up? Why is my method returning Infinity?
问题
public class Vehicle {
int passengers;
int fuelcap;
int mph;
Vehicle(int p, int f, int m) {
passengers = p;
fuelcap = f;
mph = m;
}
double fuelNeeded(int miles) {
return (double) miles / mph;
}
}
public class STUFF {
public static void main(String[] args) {
Vehicle minivan = new Vehicle(7, 16, 21);
Vehicle sportscar = new Vehicle(2, 14, 12);
double gallons;
int dist = 252;
gallons = minivan.fuelNeeded(dist);
System.out.println(gallons);
gallons = sportscar.fuelNeeded(dist);
System.out.println(gallons);
}
}
Output:
12.0
21.0
If you have been getting "Infinity" as output, the issue might have been due to incorrect assignments in the Vehicle
constructor. Make sure to assign the parameters to the corresponding instance variables, as shown in the corrected code above. This should fix the problem and provide you with the correct output.
英文:
public class Vehicle {
int passengers;
int fuelcap;
int mph;
Vehicle(int p, int f, int m) {
p = passengers;
f = fuelcap;
m = mph;
}
double fuelNeeded (int miles) {
return (double) miles/mph;
}
}
public class STUFF {
public static void main(String[] args) {
Vehicle minivan = new Vehicle(7, 16, 21);
Vehicle sportscar = new Vehicle(2, 14, 12);
double gallons;
int dist = 252;
gallons = minivan.fuelNeeded(dist);
System.out.println(gallons);
gallons = sportscar.fuelNeeded(dist);
System.out.println(gallons);
}
}
Output:
Infinity
Infinity
I have been stuck on this problem for quite sometimes now, I'm not sure where I messed up but the method keeps outputing the result as Infinity, it would be much helpful if you guys can give me some insights to where and how the code was wrong. Thank you so much!!
答案1
得分: 1
你正在将局部变量(p
,f
,m
)赋予全局变量的值,但你应该反过来进行:
Vehicle(int p, int f, int m) {
passengers = p;
fuelcap = f;
mph = m;
}
因为这个原因,在fuelNeeded
函数中你正在进行除以0的操作,导致结果为Infinity
。
英文:
You are assigning the local variables (p
, f
, m
) the values of your global variables, but you should be doing it the other way around:
Vehicle(int p, int f, int m) {
passengers = p;
fuelcap = f;
mph = m;
}
Because of this, you are dividing by 0 in fuelNeeded
, which results in Infinity
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论