[英]Exiting a for loop from an if in the for loop?
我收到“有與該信息匹配的航班信息”“記錄了旅客的詳細信息並完成了預訂”
但是然后我也得到“沒有飛往這個目的地的航班”
for (int k = 0;k <=4; k++)
{
if (destination.equalsIgnoreCase(flights[k].getDestination()))
{
k = 5;
System.out.print("\nEnter desired day of departure: ");
day = scan.nextLine();
System.out.println("\f");
if (day.equalsIgnoreCase(flights[k].getDay()))
{
if (flights[k].getBookedSeats() < 100)
{
passengers[0 + bookedSeats].setName(name);
passengers[0 + bookedSeats].setAddress(address);
passengers[0 + bookedSeats].setEmail(email);
passengers[0 + bookedSeats].setOnFlight(k);
flights[k].increaseBookedSeats();
System.out.println("\nA flight is available matching this information");
System.out.println("Passenger's details recorded and booking completed");
}else{
System.out.println("\nThere are no seats available on this flight");
}
}else
{
System.out.println("\nThere are no flights flying to this destination on this day");
}
}else if(!destination.equalsIgnoreCase(flights[k].getDestination()) && k==4)
{
System.out.println("\nThere are no flights flying to this destination");
}
}
您可以在if
條件中添加break
語句,以確保循環中斷。
當您在循環完成每次迭代之前找到適合您的乘客的有效航班時,就會出現此問題。 在if語句中將k
設置為5是朝正確方向邁出的一步,但不起作用,因為您隨后將在該塊的其余部分中使用flights[5]
。
您可以使用break
語句而不是k = 5
,但是如果您想確保以后的代碼易於維護,則可以通過使用while循環和布爾值來指定完成時間,從而使意圖更清晰。
int k = 0;
bool done = false;
while (!done && k <= 4)
{
if (destination.equalsIgnoreCase(flights[k].getDestination()))
{
k = 5;
System.out.print("\nEnter desired day of departure: ");
day = scan.nextLine();
System.out.println("\f");
if (day.equalsIgnoreCase(flights[k].getDay()))
{
if (flights[k].getBookedSeats() < 100)
{
passengers[0 + bookedSeats].setName(name);
passengers[0 + bookedSeats].setAddress(address);
passengers[0 + bookedSeats].setEmail(email);
passengers[0 + bookedSeats].setOnFlight(k);
flights[k].increaseBookedSeats();
System.out.println("\nA flight is available matching this information");
System.out.println("Passenger's details recorded and booking completed");
// added this line:
done = true;
}else{
System.out.println("\nThere are no seats available on this flight");
}
}else
{
System.out.println("\nThere are no flights flying to this destination on this day");
}
}else if(!destination.equalsIgnoreCase(flights[k].getDestination()) && k==4)
{
System.out.println("\nThere are no flights flying to this destination");
}
k++;
}
有人認為使用break
很好,在很多情況下我都同意。 但是,當您返回查看代碼(或其他人查看)時,很高興知道for
循環將絕對執行它指定的次數,但是while
循環可能會提前退出。 它只是使將來的事情變得容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.