[英]How to make goto statements when not in scope in C#?
我目前正在用 C# 制作的控制台 window 中開發一個小彩票游戲。
我添加了一個功能,讓用戶隨機選擇他將在他的票上擁有的 6 個號碼,但我注意到我的隨機數生成器有時會生成相同的號碼,即使理論上你只能有一個號碼,所以我建立了這個檢查以查看是否有number 是相同的,只是注意到我不能 go 返回隨機化一個新的數字列表,因為goto
function 不能 go 跳出循環 (CS0159)。 還有其他方法嗎?
代碼:
Console.WriteLine("\nRandomized 6 numbers: ");
// Randomize 6 numbers in for the array randomList
for (int z = 0; z <= 5; z++)
{
SameNum:
int rndNum = rnd.Next(1, 50);
randomList[z] = rndNum;
}
// Once the list is done check if any elements of the array
// are the same and if yes go back to SameNum to generate a new
// List of 6 numbers
for (int a = 0; a <= 5; a++)
{
for (int b = 0; b <= 5; b++)
{
while (randomList[a] == randomList[b])
{
goto SameNum;
}
}
}
// Display the random list if there are no same numbers
for (int c = 0; c <= 5; c++)
{
Console.WriteLine(randomList[c] + " ");
}
可能的解決方案。
List<int> digits = new List<int>();
int z= 0;
while(z <= 5)
{
int rndNum = rnd.Next(1, 50);
if(!digits.Contains(rndNum))
{
digits.Add(rnbNum);
z++;
}
}
int[] randomList = digits.ToArray();
digits.Clear();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.