我有一個循環,讀取程序啓動時文本文件中的行數,然後根據行數,它會將該許多對象存儲到新的(Vehicle [])數組(最多4個)中。試圖阻止從無限循環的循環,但也保持它從每次運行「休息」
public boolean addVehicle(Vehicle[] Honda) throws FileNotFoundException
{
Scanner reader = new Scanner(file);
String strLine = "";
if(canAddVehicle() == true)
{
for(int i = 0; i < vehicles.length;i++)
{
System.out.println("This file is: " + file);
int counter = 0;
if(vehicles[i] == null)
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(this.file);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
//Declare objects inside the array.
Honda[counter] = new Vehicle();
Honda[counter].readRecord(reader);
vehicles[counter] = Honda[counter];
counter++;
}
strLine = "";
//Close the input stream and scanner
reader.close();
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
break;
}
}
return true;
}
我遇到的麻煩的部分是這一行:
if(vehicles[i] == null)
程序啓動時,用戶可以選擇新的車輛添加到陣列後。如果你逐行閱讀代碼,你可以看到它開始於i = 0,並且讓我們說當程序第一次運行它時發現了2行值,所以它將2個對象存儲到數組中。 取值0和1。這意味着當用戶添加一輛新車時,它將跳過if(vehicles[i] == null)
,因爲spot [0]不爲空,它包含程序開始處的值。
然後,它會導致break;
並將您踢出該方法,而不會通過for循環檢查數組中是否存在任何其他空值。 我可能在這裏做什麼?
如果你想了解你的程序,我建議在調試器中逐句通過你的代碼。希望這會幫助你找到你需要放置'break'的地方;' –
也是,你在哪裏增加'i'? –
他增加我說的地方「i ++」 –