2012-12-31 24 views
-2

我想要求用戶輸入10個數字並將它們存儲到數組中。然後提示用戶輸入任意數字以檢查數字中是否已存儲數字。當我輸入任何號碼時,屏幕將消失,如果號碼已經存在,我無法驗證。請看我的代碼。提前致謝。C#檢查數組中是否存在數字

static void Main(string[] args) 
    { 
     int[] numCheck = new int[10]; 
     int[] userInput = new int[1]; 

     Console.WriteLine("Please enter 10 numbers: "); 

     for (int i = 0; i < 10; i++) 
     { 
      Console.Write("Number {0}: ", i + 1); 
      numCheck[i] = int.Parse(Console.ReadLine()); 
     } 

     Console.WriteLine("Please enter any number to check if the number already exist"); 

     for (int j = 0; j <= 10; j++) 
     { 
      if (userInput == numCheck) 
      { 
       Console.Write("The number {0} is in the index", numCheck); 
       userInput[j] = int.Parse(Console.ReadLine()); 
      } 

      else 
      { 
       Console.Write("The number {} is not in the index", numCheck); 
      } 
     } 
+4

您有問題要問? –

+0

可能想查看Array.Contains函數http://msdn.microsoft.com/en-us/library/bb384015(v=vs.100).aspx – VisualMelon

回答

1

建議替代方案:

static void Main(string[] args) 
{ 
    int[] numCheck = new int[10]; 
    Console.WriteLine("Please enter 10 numbers: "); 

    for (int i = 0; i < 10; i++) 
    { 
     Console.Write("Number {0}: ", i + 1); 
     numCheck[i] = int.Parse(Console.ReadLine()); 
    } 

    Console.WriteLine("Please enter any number to check if the number already exist"); 
    int userInput = int.Parse(Console.ReadLine()); 

    for (int i = 0; i < 10; i++) 
    { 
     if (userInput == numCheck[i]) 
     { 
      Console.Write("FOUND NUMBER"); 

      break; 
     } 
    } 
} 
1

不應該這樣:

if (userInput == numCheck) 

要:

if (userInput[0] == numCheck[j]) 
2

你只需要1個項目從用戶因此無需聲明數組

int userInput; 

//read userInput 

if (numCheck.Any(i => i == userInput)) 
{ 
    Console.Write("The number {0} is in the index", userInput); 
} 
else 
{ 
    Console.Write("The number {} is not in the index", userInput); 
}