2017-02-10 70 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