我想通過用戶輸入讀取字符串並將其存儲在數組中。該字符串必須是由空格分隔的單個數字數字。用戶將輸入完全20個數字,並且連續兩次不會出現數字。讀取一個字符串,將其分開,並將其放入一個數組中C#
例字符串:
1 2 9 6 3 2 4 5 8 1 3 6 4 7 8 2 1 9 6 3
下面是代碼我必須這樣做,以及錯誤檢查和它不能正常工作。我想我正在考慮錯誤檢查。在下面的代碼中,refString
是大小爲20的int數組。
case 2:
bool validated = false;
Console.WriteLine("\nPlease enter a 20 character reference string, each separated by a single space");
Console.WriteLine("A number should not occur twice in a row, ex: 1 5 4 4 6");
Console.WriteLine("Each character must be an integer 1-9");
Console.WriteLine("Example reference string: 1 2 3 4 2 1 5 6 2 1 2 3 7 6 3 2 1 2 3 6");
Console.WriteLine("\nEnter reference string: ");
string s = Console.ReadLine();
refString = s.Split(' ').Select(n => Convert.ToInt32(n)).ToArray(); //split string and add numbers into array
int totalCount = refString.Length;
//if the user entered exactly 20 numbers, check to see if any of the numbers occur twice in a row
if (totalCount == 20)
{
for (i = 1; i < 20; i++)
{
while (refString[i] == refString[i - 1]) //make sure two of the same number side by side do not occur
{
break;
}
}
}
while (totalCount != 20 || !validated)
{
for (i = 1; i < 20; i++)
{
while (refString[i] == refString[i - 1]) //make sure two of the same number side by side do not occur
{
Console.WriteLine("\nError: reference string is NOT 20 numbers");
Console.WriteLine("\nEnter reference string: ");
s = Console.ReadLine();
refString = s.Split(' ').Select(n => Convert.ToInt32(n)).ToArray();
totalCount = refString.Length;
}
}
if (totalCount == 20)
{
for (i = 1; i < 20; i++)
{
while (refString[i] == refString[i - 1]) //make sure two of the same number side by side do not occur
{
break;
}
}
}
}
break;
}
感謝您的回答! – user3015999