我的代码有问题,我通过 ArrayList
获取 currentVehicle
并将其返回以在 GUI 界面中显示。
我在到达 ArrayList
末尾时遇到问题,并且它开始返回“null”。由于它返回“null”,我无法返回到以前的车辆,因为 currentVehicle
值现在被指定为“null”。
我尝试使用while
循环重新启动循环,else和else if
循环并使用lastIndexOf
和isEmpty
检查 ArrayList 并尝试让它重新循环。
下面是 ArrayList
的代码,我在其中搜索列表中的下一个车辆,并且我相信可能存在修复程序。
Showroom.java
public Vehicle nextVehicle()
{
Vehicle nV = null;
try
{
if (currentVehicle < vehicleArray.size())
{
nV = vehicleArray.get(currentVehicle++);
}
}
catch(Exception e)
{
System.out.println("No more vehicles listed");
}
return nV;
}
GUIMain 是输出发生的地方,我正在打印到 JPanel TextArea
GUIMain.java
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == nextButt)
{
log.setText(null);
log.append("" + s.nextVehicle());
}
}
log.setText(null);
清除 JPanel
文本框以显示下一个车辆,并且 log.append(""+ s.nextVehicle( ));
将 currentVehicle 打印到 JPanel
TextArea
上。
任何帮助将不胜感激。如果需要任何其他代码或需要 SSCCE,我会继续完成它。
最佳答案
好吧,如果您想在到达最后一辆车后返回第一辆车,请执行以下操作:
public Vehicle nextVehicle()
{
Vehicle nV = null;
try
{
if (currentVehicle < vehicleArray.size())
{
nV = vehicleArray.get(currentVehicle++);
} else {
if (vehicleArray.size() > 0) {
nV = verhicleArray.get(0);
currentVehicle = 1;
}
}
}
catch(Exception e)
{
System.out.println("No more vehicles listed");
}
return nV;
}
关于java - 一旦完成遍历 ArrayList,如何阻止该方法返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26686361/