【发布时间】:2021-01-20 23:07:16
【问题描述】:
我正在上入门级大学编程课,这可能是一个新手问题,但我无法在其他地方找到答案,也无法弄清楚为什么 Java 会从我的第二个 Conveyor 实例中分配参数两个实例。
这是我的 Conveyor 课程:
public class Conveyor
{
//fields
private static String type;
private static double speed; //Speed is measured in m/s (meters/second)
//constructors
public Conveyor(String type, double speed)
{
this.type = type;
this.speed = 0;
this.speed = setSpeed(speed);
}
//methods
public String getType()
{
return this.type;
}
public double getSpeed()
{
return this.speed;
}
public double setSpeed(double speed)
{
if(speed <= 0)
{
this.speed = this.speed;
}
else
{
this.speed = speed;
}
return this.speed;
}
public double timeToTransport(double distance)
{
double t = distance / getSpeed();
return t;
}
}
以及用于测试它的 Conveyor 应用程序:
public class ConveyorApp
{
public static void main(String[] args)
{
Conveyor c1 = new Conveyor("flat belt",0.9);
Conveyor c2 = new Conveyor("roller", -0.5);
System.out.printf("Conveyor 1: %s conveyor with a speed of %.1f\n", c1.getType(), c1.getSpeed());
System.out.printf("Time to transport an item 50m: %.1f\n\n", c1.timeToTransport(50));
System.out.printf("Conveyor 2: %s conveyor with a speed of %.1f\n", c2.getType(), c2.getSpeed());
System.out.printf("Time to transport an item 50m: %.1f\n\n", c2.timeToTransport(50));
}
}
如果我将第二个实例移到第一个的打印语句下方,它会产生预期的行为并打印:
Conveyor 1: flat belt conveyor with a speed of 0.9
Time to transport an item 50m: 55.6
Conveyor 2: roller conveyor with a speed of 0.0
Time to transport an item 50m: Infinity
否则按照上面显示的顺序,这是我的输出:
Conveyor 1: roller conveyor with a speed of 0.0
Time to transport an item 50m: Infinity
Conveyor 2: roller conveyor with a speed of 0.0
Time to transport an item 50m: Infinity
我做错了什么?
【问题讨论】:
-
看
Understanding Class Members????????docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
标签: java class instance instance-variables