Need to remove duplicate values from C# program

前端 未结 5 1657
南方客
南方客 2020-12-22 07:49

I need some help with a C# program that i am creating. So in this scenario i am inputting duplicate values into the program. For Example, a,b,b,c,c.
The exercise is that

5条回答
  •  天命终不由人
    2020-12-22 08:19

    Using a hashtable (Generic Dictionary) is an efficient way to determine if an entered character has already been encountered.

    Also, the Char.IsLetter method in the .NET framework is a great way to check for bad data.

    static void Main(string[] args) {
        Dictionary charsEntered = new Dictionary();
    
        Console.WriteLine("Please enter 5 characters, each on a separate line.");
        while (charsEntered.Count() < 5) {
            Console.WriteLine("Enter a character:");
            char[] resultChars = Console.ReadLine().ToCharArray();
    
            if(resultChars.Length != 1 || !Char.IsLetter(resultChars[0])) {
                Console.WriteLine("Bad Entry. Try again.");
            } else {
                char charEntered = resultChars[0];
                if (charsEntered.ContainsKey(charEntered))
                    Console.WriteLine("Character already encountered. Try again.");
                else
                    charsEntered[charEntered] = true;
            }
        }
    
        Console.WriteLine("The following inputs were entered:");
        Console.WriteLine(String.Join(", ", charsEntered.Keys));
        Console.ReadLine();
    }
    

提交回复
热议问题