【问题标题】:C# Checking users input before placing it into an arrayC#在将用户输入放入数组之前检查用户输入
【发布时间】:2013-10-25 04:26:53
【问题描述】:

我希望用户输入 10 到 100 之间的 10 个数字,它们必须是唯一的,否则它会要求您输入一个新数字。我能够让数组工作并接受 10 个数字,但它不会检查它与其他数字或在我的值之间。在这段代码下面是我编写的一个有效但不是循环的代码。任何帮助表示赞赏。

    int a;
      int[] arr = new int[10]; // The size of the array is 10

      // Here the values are accepted from the user
      for (a = 0; a <= 9; a++)
      {
      Console.Write("\nEnter your number:\t");
      //Here is were all the storing is done
      arr[a] = Convert.ToInt32(Console.ReadLine());
      //Here is my check values for the inputted numbers
      if (arr[a] < 10 || arr[a] > 100)  // I tried using brackets and && nothing worked
      {
      // If they do not meet the correct information
      Console.WriteLine
      ("You did not enter a valid number.");
      --arr[a];

      }
      else
      {
      //When they do meet the correct values
      Console.WriteLine("Thanks for entering the number " + arr[a]);
      }
      }

      Console.WriteLine("\n");
      //Here the inputted values are printed out
      for (a = 0; a < 10; a++)
      {
      Console.WriteLine("You entered the number {0}", arr[a]);
      }
      Console.ReadLine();

我编写的有效代码不是循环。我正在尝试用更少的代码和循环来完成这个精确的代码。

            Console.WriteLine("Please enter 10 numbers between 10 and 100. They cannot be identical.");
            Retrypoint1:
            int a = int.Parse(Console.ReadLine());
            if ((a > 10) && (a < 100));

            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100.\r\n Please try again.");
                goto Retrypoint1;
            }
            Retrypoint2:
            int b = int.Parse(Console.ReadLine());
            if ((b > 10) && (b < 100) && (b != a)) ;
            else
            {

                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint2;

            }
            Retrypoint3:
            int c = int.Parse(Console.ReadLine());
            if ((c > 10) && (c < 100) && (c != a) && (c != b)) ;
            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint3;
            }
            Retrypoint4:
            int d = int.Parse(Console.ReadLine());
            if ((d > 10) && (d < 100) && (d != a) && (c != b) && (d != c)) ;
            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint4;
            }
            Retrypoint5:
            int e = int.Parse(Console.ReadLine());
            if ((e > 10) && (e < 100) && (e != a) && (e != b) && (e != c) && (e != d)) ;
            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint5;
            }
            Retrypoint6:
            int f = int.Parse(Console.ReadLine());
            if ((f > 10) && (f < 100) && (f != a) && (f != b) && (f != c) && (f != d) && (f != e)) ;
            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint6;
            }
            Retrypoint7:
            int g = int.Parse(Console.ReadLine());
            if ((g > 10) && (g < 100) && (g != a) && (g != b) && (g != c) && (g != d) && (g != e) && (g != f)) ;
            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint7;
            }
            Retrypoint8:
            int h = int.Parse(Console.ReadLine());
            if ((h > 10) && (h < 100) && (h != a) && (h != b) && (h != c) && (h != d) && (h != e) && (h != f) && (h != g)) ;
            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint8;
            }
            Retrypoint9:
            int i = int.Parse(Console.ReadLine());
            if ((i > 10) && (i < 100) && (i != a) && (i != b) && (i != c) && (i != d) && (i != e) && (i != f) && (i != g) && (i != h)) ;
            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint9;
            }
            Retrypoint10:
            int j = int.Parse(Console.ReadLine());
            if ((j > 10) && (j < 100) && (j != a) && (j != b) && (j != c) && (j != d) && (j != e) && (j != f) && (j != g) && (j != h) && (j != i)) ;
            else
            {
                Console.WriteLine("The number you entered does not fall between 10 and 100 \r\n or is identical to one of the other numbers. Please try again");
                goto Retrypoint10;
            }
            Console.WriteLine("The numbers you entered were " + a + ", " + b + ", " + c + ", " + d + ", " + e + ", " + f + ", " + g + ", " + h + ", " + i + " & " + j);
            Console.WriteLine("Please press enter to continue");
            Console.ReadKey();

【问题讨论】:

  • 您是否有特殊原因试图避免循环语句?
  • 您不需要每次都循环检查数组中是否存在该数字。相反,使用Contains

标签: c# arrays loops


【解决方案1】:

问题出在这里:

 if (arr[a] < 10 || arr[a] > 100)  // I tried using brackets and && nothing worked
 {
 // If they do not meet the correct information
 Console.WriteLine
 ("You did not enter a valid number.");
 --arr[a];
 }

使用--arr[a],您可以减少用户输入的值,也可以将其丢弃。你想写的是--a

要检查用户是否输入了双倍数字,您可以通过添加 if(…) 来检查

 || arr.Take(a).Contains(arr[a])

【讨论】:

  • 谢谢你,这让我发疯了!!!这两小块解决了一切。您真棒!感谢您的帮助
【解决方案2】:

你的问题在这里:

--arr[a];

您应该递减a,而不是数组中的值。试试这个:

a--;

【讨论】:

  • 抱歉,我忘了回答“唯一”约束。您应该将 if 语句更新为:if ((arr[a] &lt; 10 || arr[a] &gt; 100 ) &amp;&amp; !arr.Contains(arr[a])) 您可能需要包含对 System.Linq 的引用
  • !arr.Contains(arr[a]) 始终为 false,因为 arr 始终在位置 a 包含其元素。还要注意arr 有很多空槽,所以你必须防止它们被检查。
  • 谢谢,我自己也注意到了 :) 应该是 arr.Where(i =&gt; i == arr[a]).Count() &gt; 1。我没有费心检查空槽,因为它们被初始化为 0,这已经被 arr[a] &lt; 10 捕获,但你是对的。在实际将值设置到数组中之前进行验证会好得多。
【解决方案3】:

一些问题,其中至少有两个已经被提及:

  1. 您的代码不会检查输入的文本是否实际上是数字。如果用户输入的内容不是数字,Convert.ToInt32 将抛出异常。

  2. 使用--arr[a],您正在递减数组中a 位置的值,而不是a 的值。

  3. 不要在没有非常充分理由的情况下goto。即使在测试代码中。

这里有一些代码应该涵盖了您正在尝试做的大部分事情:

int[] arr = new int[10];

for (int a = 0; a < 10; )
{
    // Get number from user
    Console.Write("Enter number: ");
    string entered = Console.ReadLine();
    int val;

    // check for valid integer entered
    if (!Int32.TryParse(entered, out val))
        Console.WriteLine("Invalid number '{0}'", entered);
    // check number in allowed range
    else if (val < 10 || val > 100)
        Console.WriteLine("Value '{0}' out of allowed range (10-100)", val);
    // check number not already supplied
    else if (a > 0 && arr.Take(a).Contains(val))
        Console.WriteLine("Value '{0}' already entered");
    // add to array
    else
    {
        arr[a++] = val;
        Console.WriteLine("Added value '{0}'.  {1} remaining.", val, 10 - a);
    }
}

【讨论】:

  • 所以你在第一个语句中的意思是我应该编写代码来接受输入,检查输入是否是一个数字,然后要么把它扔掉,要么继续检查?
  • 如果您期待一个数字并且用户输入了一个非数字值 - 例如他们的名字 - 您的代码将在尝试将输入转换为数字期间死亡。例如,使用 TryParse 可以保护您免受这种情况的影响。
【解决方案4】:

这样的东西应该适合你,我正在使用 TryParse 过滤掉非数字字符和一个 do while 循环,我还使用 Contains Linq Extension method 来检查重复项。看看这是否适合你。

static void Main(string[] args)
{
    int[] arr = new int[10];
    int count = 0;
    int a;
    do
    {
        if (int.TryParse(Console.ReadLine(), out a)) //Verify that input is numeric
        {
            if ((a > 10) && (a < 100))  //Check Constraints
            {
                if (!arr.Contains(a))   //Check for duplicates
                {
                    arr[count] = a;    //Only if we get here then input into array
                    count++;           //Increment to next Index
                }
            }
        }
    } while (count < 10);             //Rinse and repeat to you get 10 valid entries

    Console.ReadLine();
}

【讨论】:

    【解决方案5】:

    您可以尝试以下进行更多验证(请参阅注释代码):

    static void Main(string[] args)
        {
            int[] arr = new int[10]; // The size of the array is 10
            int input;
            int savedNumCount = 0;
            const int MIN = 10;  // Use constant to set the range instead
            const int MAX = 100; // of typing them in code
    
            Console.WriteLine("Please enter 10 numbers between 10 and 100. They cannot be identical.");
            do
            {
                if (int.TryParse(Console.ReadLine(), out input) == false)
                { // Check if number is entered
                    Console.WriteLine("Please enter a number.");
                    continue;
                }
                if (input < MIN || input > MAX)
                { // Check range
                    Console.WriteLine("The number you entered does not fall between 10 and 100.\r\n Please try again.");
                    continue;
                }                
                if (savedNumCount == 0)
                { // Compare with existing numbers
                    arr[savedNumCount] = input; // No checking for 1st input
                    savedNumCount++;
                }
                else
                {
                    if (!arr.Contains(input))
                    {
                        arr[savedNumCount] = input;
                        savedNumCount++;
                    }
                    else
                    {
                        Console.WriteLine("The number you entered is identical to one of the other numbers. Please try again");
                    }
                }
            }
            while (savedNumCount < arr.Length);
    
            string result = "The numbers you entered were ";
            foreach (int num in arr)
                result += num.ToString() + "  ";
            Console.WriteLine(result);
            Console.WriteLine("Please press enter to continue");
            Console.ReadKey();
        }
    

    【讨论】:

      【解决方案6】:

      我不希望首先存储无效输入:

      Console.Write("\nEnter your number:\t");
      int input = Convert.ToInt32(Console.ReadLine());
      if (input < 10 || input > 100 || arr.Contains(input))
          Console.WriteLine("You did not enter a valid number.");
      else
      {
          arr[a] = input;
          //When they do meet the correct values
          Console.WriteLine("Thanks for entering the number " + arr[a]);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-27
        • 2014-12-20
        • 1970-01-01
        • 1970-01-01
        • 2019-06-20
        • 1970-01-01
        相关资源
        最近更新 更多