我有一個關于變數結果的問題。我有一個要求輸入數字的函式。它回傳 AskForNumber 函式的第一個輸入。誰能幫幫我,好嗎?我是C#的新手,不知道很多應該知道的細節。我希望得到您的幫助:))
這是在C#中的一個函式。
這是主函式
static void Main() {
string playersNum = AskForNumber(numberLength)。
Console.WriteLine(playerNum)。
}
這就是詢問數字的函式
static string AskForNumber(int numberLength) /span> {
Console.WriteLine($"Write number of Length {numberLength}") 。
string number_string = Console.ReadLine();
if (!CheckCondition(numberLength, number_string)) {
AskForNumber(numberLength);
}
return number_string;
}
那么數字應該在CheckCondition函式中被檢查,并回傳它的真或假
。static bool CheckCondition(span class="hljs-built_in">int length, string number_string) {
if (!int.TryParse(number_string, out int number) {
Console.WriteLine("thats nan!!")。
return false;
} else if (number_string.Length != length) {
Console.WriteLine($"number's length must be {length} digits") 。
return false。
}
return true;
取決于它應該只在變數中的數字為真時回傳
這就是終端的結果寫入長度為4的數字。
qwerty
這是南!
1234
qwerty (Thats the result of the Console.WriteLine(playerNum); in the main function)
uj5u.com熱心網友回復:
這是因為你在反復呼叫AskForNumber()。
在Main中,您第一次呼叫AskForNumber()并輸入 "querty"。然后CheckCondition方法回傳false,因為它不是一個數字,你再次呼叫AskForNumber()。然后你輸入 "1234",CheckCondition回傳true,因此 "1234 "被第二次呼叫AskForNumber()。"1234 "被回傳到第一次呼叫AskForNumber()時,你沒有對回傳的值做任何處理,只是離開if塊并回傳存盤在number_string的值。但是由于你沒有將第二次呼叫AskForNumber()的回傳值分配給這個變數,它仍然包含 "qwerty",因此Main接收 "qwerty "并列印它。
只要將你的代碼改為
static string AskForNumber(int numberLength) /span> {
Console.WriteLine($"Write number of Length {numberLength}") 。
string number_string = Console.ReadLine();
if (!CheckCondition(numberLength, number_string)) {
return AskForNumber(numberLength); // Return statement added here.
}
return number_string;
}
并且將按預期作業。
uj5u.com熱心網友回復:
你可以先回傳值然后呼叫方法,或者在回傳值的同時呼叫方法。
static string AskForNumber(int numberLength) /span> {
Console.WriteLine($"Write number of Length {numberLength}") 。
string number_string = Console.ReadLine();
if (!CheckCondition(numberLength, number_string)) {
return AskForNumber(numberLength); /* this will call the method in a return statement
}
return number_string;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/323090.html
標籤:
上一篇:將日期從DataGridView提取到DateTimePicker
下一篇:用.NET連接到AWSMQTT
