[英]C# How to make use of return true/false from a method (outside of loop) called from within a while loop
我正在嘗試編寫一個程序,讓我將名稱列表及其各自的電影評級輸入到一個數組中(會做一個列表,但課程材料要我使用數組)。 在將名稱添加到數組之前,我想確保輸入了有效的評級。
我目前正在使用循環遍歷數組長度的 for 語句,並讓用戶以這種方式將每部電影輸入到列表中。 這發生在一個 while 循環中,如果在將名稱提交給 Array 之前評級無效,則使他們重新輸入名稱。 我通過調用一個方法來檢查名稱,該方法使用分配有當前輸入的名稱和評級的臨時字符串,這將進行一些條件檢查並根據結果返回 false 或 true。 但是我這樣做的方式根本不起作用..
問題是我不知道如何實際使用我的方法返回的 bool 語句:
string[] filmNames = new string[ArrayLength];
for (int i = 0; i < filmNames.Length; i = i + 1)
{
bool ratingFail = true;
int displayNumber = i + 1;
while (ratingFail)
{
Console.Write($"> Enter the Name and Rating of film number {displayNumber} of {ArrayLength}: ");
string checkRating = Console.ReadLine();
CheckRating(checkRating); // currently just does "return false;" for testing purposes
if (true) // this statement is clearly not effected by whatever the return value is from above method. Why? What to do?
{
ratingFail = true;
}
else
{
filmNames[i] = checkRating; // this bit is marked as unreachable, which is is.
ratingFail = false;
}
}
}
我的測試方法:
public static bool CheckRating(string checkRating)
{
return false;
}
我對編程和 C# 非常(一周)新手,所以在回答時請記住,我可能不理解指代 scope 之外的編程術語的特定行話,但我會谷歌並研究如果沒有辦法簡化你想說的話,我會盡力而為。 感謝您的時間和精力。
bool ret = CheckRating(checkRating); // currently just does "return false;" for testing purposes
if (ret)
{
[...]
}
或者,就像 Sinatr 的評論一樣:
if(CheckRating(checkRating))
{
[...]
}
if (true) // this statement is clearly not effected by whatever the return value is from above method. Why? What to do?
{
ratingFail = true;
}
這將始終為真,因為您正在創建一個始終為真的變量。 你要這個:
ratingFail = CheckRating(checkRating)
if (!ratingFail) {
The rating is valid, do stuff here.
}
如果 ratingFail 為真,循環將繼續。
這假定 CheckRating 在輸入無效時返回 true,在輸入有效時返回 false。 這里的變量命名很混亂,我建議你重構。
我會這樣做,假設 CheckRating 在有效時返回 true:
for (int i = 0; i < filmNames.Length; i = i + 1)
{
bool ratingValid; // Defaults to false
int displayNumber = i + 1;
while (!ratingValid)
{
Console.Write($"> Blablabla: ");
string input = Console.ReadLine();
ratingValid = CheckRating(input);
}
// Do stuff if rating is valid here. If you got here, rating is valid.
}
// 由 iluvpancakes 編輯 // 我決定添加@Sinatr 的評論,因為那是我個人最終使用的解決方案的(版本):
if(CheckRating(checkRating))
{
[do stuff and things]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.