2017-02-10 47 views
0

我的代码:C#做一些

string[] code = new string[9]; 
int[] intCode = new int[9]; 

int cd = 0, dvd = 0, video = 0, book = 0; 
for (int i = 0; i < 10; i++) 
{ 

    Console.Write("Enter code#{0}: ",i+1); 
    code[i] = Console.ReadLine(); 
    if (code[i].Length==5) 
    { 
     intCode[i] = Convert.ToInt32(code[i]); 
     intCode[i] /= 100000; 
     if (intCode[i] == 1) 
     { 
      cd++; 
      break; 

     } 
     if (intCode[i] == 2) 
     { 
      dvd++; 
      break; 
     } 
     if (intCode[i] == 3) 
     { 
      video++; 
      break; 
     } 
     if (intCode[i] == 4) 
     { 
      book++; 
      break; 
     } 
    } 
    else 
    { 
     Console.WriteLine("INVALID CODE"); 

    } 

} 

基本上我想要做的是其他{做一些事在这里}要求用户重新输入数字,而不是要为循环和icrementing我并要求用户输入新的。

+3

你”有没有听说过“不”的情况?它看起来像你的代码中有逻辑失败。想更多你作为一个人会如何解决这个问题,并试着写下来解释给不知道的人 – BugFinder

+4

或者'while'循环也许?很难告诉你在这里寻找什么...... –

+0

你将一个5位数的数字除以6位数,并期望结果是1,2,3或4.如果我是你,我会只需检查'if(code [i] [0] =='1')'等等。 –

回答

1

在else块:

else 
{ 
    Console.WriteLine("INVALID CODE"); 
    i -= 1; 
} 
+0

非常感谢你:) –

+0

我只是猜你想要用户重新输入它,所以只是再次,然后它是好的。 – PSo

+0

耶是行之有效的。 –

0

使用,而与开关的组合:

 string[] code = new string[9]; 
     int[] intCode = new int[9]; 
     int cd = 0, dvd = 0, video = 0, book = 0; 
     for (int i = 0; i < 10; i++) 
     { 
      bool isCorrectInput = false; 
      while (!isCorrectInput) 
      { 
       isCorrectInput = true; 
       Console.Write("Enter code#{0}: ", i+1); 
       code[i] = Console.ReadLine(); 
       if (code[i].Length == 1) 
       { 
        intCode[i] = Convert.ToInt32(code[i]); 
        // intCode /= 100000; 
        switch (intCode[i]) 
        { 
         case 1: 
          cd++; 
          break; 
         case 2: 
          dvd++; 
          break; 
         case 3: 
          video++; 
          break; 
         case 4: 
          book++; 
          break; 
         default: 
          isCorrectInput = false; 
          break; 
        } 
       } 
       else 
        isCorrectInput = false; 
       if (!isCorrectInput) 
        Console.WriteLine("INVALID CODE ENTERED!"); 
      } 
     } 

编辑: 应该是你现在想要什么,也纠正了错误

+0

没有工作。即使输入有效,它也表示输入无效 –

+0

您要求让用户重新输入数字的方式,在这里,输入不能有效的问题是,因为您正在检查长度等于5,并且然后除以100000,每个5位数值如果除以100000并解析为int将为0,并且0在您的方案中不处理,所以它不可能是正确的 – Pedro