嘿伙计我正在学习java我写了这个简单的代码我找不到任何错误。我无法获得Bike2 .getTime。感谢您的阅读
public class ConstructorEx3 {
int Speed;
int Distance;
int Minute;
public int getTime (){
return ((Distance/Speed)*Minute);
}
ConstructorEx3 (){
Distance = 60;
Speed = 30;
Minute = 60;
}
ConstructorEx3 (int D, int S, int M){
Distance = D;
Speed = S;
Minute = M;
}
public static void main (String []arsh){
ConstructorEx3 Bike1,Bike2;
Bike1 = new ConstructorEx3();
Bike2 = new ConstructorEx3(40,80,60);
System.out.println("Bike one is travelling at : "+ Bike1.getTime());
System.out.println("Bike two is travelling at : "+ Bike2.getTime());
}
}
答案 0 :(得分:4)
因为整数操作(40/80)*60
会给你0
。请注意,在整数计算中,40/80
将0
而非0.5
,您需要在程序中使用double
值而不是int
来获得准确答案(< em>针对您的具体案例)。
与约定相关的一些建议,
TimeCalculator
,Bike
distance
而非Distance
bike1
开头,而不是Bike1
this.distance
而不是Distance = D
答案 1 :(得分:0)
Distance = 40;
Speed = 80;
Minute - 60;
Distance / Speed = 0.5;
由于您使用的是int
,因此.5
是级联的。最后,获得0 * Minute = 0 * 60 = 0;
最好的方法是将值转换为double
并转换回来。请注意,由于在处理double到int转换时没有获得准确的结果,因此它有损。
了解我如何使用getTime()
方法解决您的问题:
public class ConstructorEx3 {
int Speed;
int Distance;
int Minute;
public int getTime (){
double v = ((double)Distance/(double)Speed);
v= v * (double)Minute;
return (int)v;
// return ((Distance/Speed)*Minute);
}
ConstructorEx3 (){
Distance = 60;
Speed = 30;
Minute = 60;
}
ConstructorEx3 (int D, int S, int M){
Distance = D;
Speed = S;
Minute = M;
}
public static void main (String []arsh){
ConstructorEx3 Bike1,Bike2;
Bike1 = new ConstructorEx3();
Bike2 = new ConstructorEx3(40,80,60);
System.out.println("Bike one is travelling at : "+ Bike1.getTime());
System.out.println("Bike two is travelling at : "+ Bike2.getTime());
}
}
输出:
Bike one is travelling at : 120
Bike two is travelling at : 30