該函式接受輸入并告訴用戶輸入的是數字還是非數字。
static string isnum()
{
Console.WriteLine("Write a number please");
string a = Console.ReadLine();
string nums = "123456789";
int cnt = 0;
for (int i = 0; i < a.Length; i )
{
for (int j = 0; j < nums.Length; j )
{
if (a[i] == nums[j])
{
cnt ;
break;
}
}
}
if (cnt == a.Length)
{
Console.WriteLine(a " is a number");
return a;
}
else
{
Console.WriteLine(a " is not a number");
return "";
}
}
isnum();
如果輸入不是數字,我希望此功能重復自己,直到輸入為數字,然后停止。這個功能現在有效,但她只作業一次。當我嘗試向函式添加一個 while 塊以使她一次又一次地運行直到輸入為數字時,我收到“并非所有代碼路徑都回傳值”錯誤。
是因為“return”陳述句結束了一個函式,因此阻止了她再次運行?我該如何解決?
非常感謝!
uj5u.com熱心網友回復:
您可以通過在它周圍創建一個回圈來解決此問題,并且當它不是數字時不要回傳。
static string isnum()
{
// just loop forever.
while (true)
{
Console.WriteLine("Write a number please");
string a = Console.ReadLine();
string nums = "123456789";
int cnt = 0;
for (int i = 0; i < a.Length; i )
{
for (int j = 0; j < nums.Length; j )
{
if (a[i] == nums[j])
{
cnt ;
break;
}
}
}
if (cnt == a.Length)
{
Console.WriteLine(a " is a number");
return a;
}
else
{
Console.WriteLine(a " is not a number");
// don't return here
}
}
}
uj5u.com熱心網友回復:
在這種情況下,最好的方法是使用 do while,因為您希望代碼至少運行一次。
您的代碼中有一個問題,當變數不是數字時回傳。看到這些修改:
static string isnum()
{
do{
Console.WriteLine("Write a number please");
string a = Console.ReadLine();
string nums = "123456789";
int cnt = 0;
for (int i = 0; i < a.Length; i )
{
for (int j = 0; j < nums.Length; j )
{
if (a[i] == nums[j])
{
cnt ;
break;
}
}
}
if (cnt == a.Length)
{
Console.WriteLine(a " is a number");
return a;
}
else
{
Console.WriteLine(a " is not a number");
}
}while(true);
}
uj5u.com熱心網友回復:
在 while 回圈中呼叫它,并回圈直到結果為數字:
string result = "";
while (result == "")
{
result = isnum();
}
Console.WriteLine("result is a number: " result);
uj5u.com熱心網友回復:
您可以嘗試在Linq的幫助下查詢字串,而不是回圈:a
using System.Linq;
...
static string isnum() {
// Keep asking user until he/she provides a number
while (true) {
Console.WriteLine("Write a number please");
string a = Console.ReadLine();
// Number is
// 1. Has at least one character
// 2. All characters of number are digits
if (a.Length > 0 && a.All(c => c >= '0' && c <= '9')) {
Console.WriteLine($"{a} is a number");
// we have a proper number, let's return int
return a;
}
Console.WriteLine($"{a} is not a number");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/487557.html
上一篇:R概率中的函式
