[英]Constructor is ignoring “for” loop(Java)
所以我感到很愚蠢,因为看起来我缺少一些琐碎的东西,并且我以前使用过循环,但是现在我们在课堂上经常使用它们,而现在看来在尝试许多不同的组合后找到问题,所以去了:
public class BusStop
{
private BusArrival[] _buses;
private int _noOfBuses;
final int MAX_ARRAY_SIZE = 1000;
//================================ CONSTRUCTORS ============================//
public BusStop(int size){ // THIS
_buses = new BusArrival[size]; // IS
// THE
for(int i=0; i< size; i++){ // PROBLEMATIC
if(_buses[i] != null){ // LOOP
_noOfBuses ++;
}
}
}
//=============================== METHODS =================================//
public int getNoOfBuses(){
return _noOfBuses;
}
public boolean add (int line, int pass, Time1 t){ // adds a BussArrival object to an empty array (if there's any).
for (int i=0; i < _buses.length; i++){
if(_buses[i] == null){
_buses[i] = new BusArrival(line, pass, t);
return true;
}
}
return false;
}
这是BusArrival类的构造函数,因此您大致了解一下:
public BusArrival(int lineNum, int pass, Time1 t){
_lineNumber = lineNum;
_noOfPassengers = pass;
_arrivalTime = t;
}
这是一个明智的类的Time1构造函数,正是如此:
public Time1(int h, int m, int s)
_hour = h;
_minute = m;
_second = s;
}
这是我的主要方法:
public class Test
{
public static void main (String [] args){
BusStop first = new BusStop(4);
Time1 one = new Time1(10,30,0);
Time1 two = new Time1(10,0,0);
first.add(1,2,one);
first.add(2,3,two);
System.out.println(first.getNoOfBuses());
}
}
不幸的是,当我这样做时,输出为“ 0”。
任何帮助,将不胜感激。 谢谢。
这是问题所在。
总线数量仅在初始化程序中分配,但在初始化程序中您未添加任何总线。 因此,您会得到0辆巴士。
添加总线时,不会更新总线数量。 所以你得到0。
您应该执行_noOfBuses++;
当您成功添加总线时。 另外,在初始化程序中取出该循环。 初始化数组时,所有条目均为空,因此循环无用:)
编辑:您似乎对代码的执行顺序感到困惑。
在main
功能中,您首先要初始化BusStop
。 这意味着他运行了初始化程序代码(包括初始化程序中的循环)。
然后,您添加了两个总线。 但是,请注意,循环已经执行,将不会再次执行,因为初始化程序只运行一次。
因此,您的循环永远不会增加_noOfBuses
每次添加新总线时,都需要增加总线数量。
public BusStop(int size){ // THIS
_buses = new BusArrival[size]; // IS
// THE
for(int i=0; i< size; i++){ // PROBLEMATIC
if(_buses[i] != null){ // LOOP
_noOfBuses ++;
}
}
}
在上面的代码中,数组_buses
仅在所有项都指向null的情况下创建。 在for循环中,您使用if语句检查是否存在任何非null值(在这种情况下该值不存在,因为数组中没有任何项)。 所以您的_noOfBuses ++;
无法到达。
首先,将另一个不带参数的构造函数添加到BusArrival类。 像这样。
public BusArrival() {}
其次,将BusStop构造函数修改为以下内容
public BusStop(int size){
_buses = new BusArrival[size];
for(int i=0; i<_buses.length; i++) {
_buses[i] = new BusArrival();
_noOfBuses ++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.