C#如何纠正数组中的错误输入

时间:2013-11-27 13:24:46

标签: c# arrays loops input

所以我需要和学生一起上课。输入必须在0-100之间,否则它不接受用户的输入。

  Console.WriteLine("How many students?");
  int num1 = Keyboard.ReadInt();
  int[] array = new int[num1];
  Console.WriteLine("Give the student grades: ");
  for (int i = 0; i < array.Length; i++)
  {
      int wrong;
      wrong = Keyboard.ReadInt();
      if (wrong > 0 && wrong <= 100)
      {
          array[i] = wrong;
      }
      else
      {
          while (wrong < 0 && wrong >= 100)
          {
              Console.WriteLine("Wrong input:");
              wrong = Keyboard.ReadInt();
          }
      }

3 个答案:

答案 0 :(得分:5)

我认为您只需要将&&更改为||

while (wrong < 0 || wrong >= 100) ...

同时,一个数字不能低于零大于99。

答案 1 :(得分:1)

您的wrong变量不能低于0且同时大于100

您应该说:如果错误小于0 大于100

这就是您需要使用||代替&&

的原因

答案 2 :(得分:0)

更改您的代码:

while (wrong < 0 || wrong >= 100)
{
     Console.WriteLine("Wrong input:");
     wrong = Keyboard.ReadInt();
}

或者您可以在此处将while更改为if

if (wrong < 0 || wrong >= 100)
{
     Console.WriteLine("Wrong input:");
     wrong = Keyboard.ReadInt();
}

或者你可以删除整个块并在else语句中以这两种方式使用它:

if (wrong > 0 && wrong <= 100)
{
    array[i] = wrong;
}
else if(wrong < 0 || wrong >= 100)
{
     Console.WriteLine("Wrong input:");
     wrong = Keyboard.ReadInt();
}

if (wrong > 0 && wrong <= 100)
{
    array[i] = wrong;
}
else 
{
     Console.WriteLine("Wrong input:");
     wrong = Keyboard.ReadInt();
}