帮忙看个Java小程序

来源:百度知道 编辑:UC知道 时间:2024/06/05 10:04:16
package ch2;

public class Car
{
protected double speed;
protected double distance;
protected double time;

public Car(){}
public Car(double s,double d)
{
this.speed=s;
this.distance=d;
}
public void getDrivingTime()
{
time=(distance/speed);
}
public double getTime()
{
return time;
}
}

package ch2;

public class Test
{
public static void main(String args[])
{

Taxi t = new Taxi(2.0,6.0,4.0);
Car c = new Car();
c.getDrivingTime();
t.getFare();
double ct = c.getTime();
double tc = t.getCarf();

System.out.println("行车时间:"+ct+"\n"+"车费:"+tc);

}
}
package ch2;

public class Taxi extends Car
{
protected double pricePerKm;
protected double carf;
public Taxi(){}

p

Car c = new Car(); 在这里是多余的,你把对Car对象的操作都换成对Texi对象的操作,把Car对象删掉就可以了

在class Car 中protected double time; 没有被赋值
你可以做多个方法:
public void setTime(double time){this.time=time;}

NaN 是无穷大,一般产生这一问题是在被零除的时候:
time=(distance/speed);

看这一句话:Car c = new Car(); 你new Car()的时候并没有把Car()的参数传进去,所以time也就无法计算了。

只要把Test类改成这样就行了:public class Test
{
public static void main(String args[])
{

Taxi t = new Taxi(2.0,6.0,4.0);
t.getDrivingTime();
t.getFare();
double ct = t.getTime();
double tc = t.getCarf();

System.out.println("行车时间:"+ct+"\n"+"车费:"+tc);

}
}

或者在new一个Car()时传递两个参数!

NaN出现的原因是:没有给car c对象属性赋值导致被除数是0.
程序已修改,加过注释。希望对你有帮助
__________________________Car.java______________________

package ch2;
public class Car
{
protected double speed;
protected double distance;
protected double time;