2017-03-09 23 views
-2

我正在處理我的項目,但我被卡住了。 控制檯項目! 如果true請求另一個輸入,則檢查用戶輸入是否已在數組中。C# - 檢查用戶輸入已經在數組中,如果是真的請求另一個輸入

+2

顯示你的代碼,你試過了什麼。 –

+0

string [] array = new string [4]; var input = Console.ReadLine(); (array.Contains(input)) Console.WriteLine(「duplicate」);如果(array.Contains(輸入)) for(int i = 0; i

+0

編輯原始帖子以添加代碼。 –

回答

0

您簡單的可以試試老式:

if (YourArray.Any(x => YourCondition)) { 
    //Ask the user for another input. 
} 
0

你可以這樣做:

while (!InArray(Console.ReadLine())); 
// ... 
public static bool InArray(string s){ 
    foreach(var item in array) { 
     if (item.Equals(s)) return false; 
    } 
    return true; 
} 
1

這可能是這樣,但因爲你做你必須做的是自己的路沒有張貼任何向我們展示了它是如何現在看起來..

int numberOfElementsInArray=100; 
string [] array = new string[numberOfElementsInArray]; 
var input = Console.ReadLine(); 
for (int i = 0; i < array.Length; i++) 
{ if (array.Contains(input)) { Console.WriteLine("What you've enter is allready contained in this array"); } else { array[i] = Console.ReadLine(); } 
+0

我怎樣才能做到這一點,當我有一個數組中的元素,而不是要求一個新的輸入,但不是跳到最後? –

+0

沒關係,在手機上,我錯過了其他條款! – Steve

+0

但它不工作,因爲它應該。 –

0
List<String> allUserInputs = new List<String>(); 
int counter = 0; 
int maxIterations = 100; 
do 
{ 
    counter++; 
    String newInput = Console.Read(); 
    if (!allUserInputs.Contains(newInput)) 
     allUserInputs.Add(newInput); 
    else 
     Console.WriteLine("\nYour input already exists. Please try again.\n") 
} while(counter <= maxIterations) 
+0

stopCriteria是什麼? –

+0

終止循環的布爾方法。 – tony

相關問題