如何在C#彩票程序中防止重复输入相同数字?
彩票程序重复输入数字问题的解决方案
你的程序已实现数字范围校验,但缺少重复输入的检查逻辑。只需在确认输入数字合法(1-25)后,检查该数字是否已存在于之前输入的数组元素中,即可解决问题。以下是修改后的完整代码:
Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Clear(); Console.WriteLine("Welcome to the lottery!"); static int GetGuess() { int guess = 0; bool ok = false; while(!ok) { Console.ForegroundColor= ConsoleColor.DarkYellow; Console.WriteLine("Type in a number between 1 and 25"); Console.ResetColor(); ok = int.TryParse(Console.ReadLine(), out guess); if(!ok) { Console.ForegroundColor= ConsoleColor.DarkYellow; Console.WriteLine("Inaccurate input"); } } return guess; } int[] myArray = new int[5]; int guess; for (int i = 0; i < myArray.Length; i++) { guess = GetGuess(); // 先检查数字范围合法性 if(guess > 0 && guess < 26) { bool isDuplicate = false; // 遍历已输入的数组元素,检查是否重复 for (int j = 0; j < i; j++) { if (myArray[j] == guess) { isDuplicate = true; break; } } if (!isDuplicate) { myArray[i] = guess; } else { Console.ForegroundColor= ConsoleColor.Red; Console.WriteLine("You've already entered this number, please input a new one!"); i--; // 停留在当前索引,让用户重新输入 } } else { Console.ForegroundColor= ConsoleColor.Red; Console.WriteLine("You didn't enter a number between 1 and 25"); i--; } } foreach (int i in myArray) Console.Write(i + " "); Random rnd = new Random(); int dragning = rnd.Next(1, 26); int rightAnswerAmount = 0; foreach(int i in myArray) { if (i == dragning) rightAnswerAmount++; } Console.ForegroundColor= ConsoleColor.Green; if (rightAnswerAmount> 0) Console.WriteLine("\nCongratz! You had {0} amount of wins!", rightAnswerAmount); else Console.WriteLine("\nYou lost all your money");
关键修改说明
- 新增
isDuplicate标记,用于判断当前输入是否与已输入数字重复 - 通过内层循环遍历数组中已填充的元素(索引0到i-1),对比当前输入值
- 若检测到重复,提示用户重新输入,并通过
i--让外层循环停留在当前索引,确保用户重新填写该位置的数字 - 优化结果输出的换行格式,提升可读性
内容的提问来源于stack exchange,提问作者Karin Wilson
相关产品推荐
相关产品推荐

