我有問題正確地擺脫這些嵌套循環。代碼試圖做的是指示客戶租用了某個電影。將電影和客戶都與arraylist對象的屬性進行比較,然後如果全部檢出電影對象的name屬性和ID屬性作爲字符串添加到另一個arraylist。只要我使用第一部電影(來自電影)和第一位顧客(來自顧客),但是如果我嘗試將其他電影進一步向其他顧客下放到我的數組列表中,則它會將租借的電影添加到customerRentedMovies數組列表中,但打印出「其他消息」。我想我需要擺脫foreach(blabla)循環嗎?或可以轉到使用?評論移除(看上去有點凌亂,可以進一步解釋,如果需要的話)擺脫嵌套循環的問題
public void RentMovie(string titel, int movieID, string name, int customerID)
{
foreach (Customer customer in customers)
{
if (name == customer.Name && customerID == customer.CustomerID)
{
foreach (MovieInfo movie in movies)
{
if (titel == movie.Titel && movieID == movie.MovieID)
{
movie.rented = true;
string rentedMovie = string.Format("{0} ID: {1}", movie.Titel, movie.MovieID);
customer.customerRentedMovies.Add(rentedMovie);
break;
}
else { Console.WriteLine("No movie with that titel and ID!"); }
}
break;
}
else { Console.WriteLine("No customer with that ID and name"); }
}
}
可能是一個愚蠢的http://stackoverflow.com/questions/324831/breaking-out-of-a-nested-loop –
爲什麼你有嵌套循環開始?找到電影,然後找到客戶。 – dlev