I am trying to create a program that is will take letters as input only and not duplicated. I am getting error when i put one letter in an input. This is what i need to do,
If you want the user to enter the values individually then you would need to request each character in a loop. Something like:
static void Main(string[] args)
{
const string validValues = "abcdefghij";
var enteredCharacters = new char[5];
for (int i = 0; i < enteredCharacters.Length; i++)
{
Console.WriteLine("Please enter a unique character between a and j");
var input = Console.ReadLine();
if (input.Length == 0)
{
Console.WriteLine("You did not enter a value.");
return;
}
if (input.Length > 1)
{
Console.WriteLine("You have entered more than 1 character");
return;
}
var character = input[0];
if (!validValues.Contains(character))
{
Console.WriteLine("You have entered an invalid character");
return;
}
if (enteredValues.Contains(character))
{
Console.WriteLine("You have already entered this character");
return;
}
enteredCharacters[i] = character;
}
// process numbers.
}
I think this more or less does what you want:
var max = 5;
var array = new char[max];
var letters = "abcdefghij";
var count = 0;
while (count < 5)
{
Console.WriteLine("Please Enter {0} Letters B/W a through j only: ", max);
var key = Console.ReadKey();
var read = key.KeyChar
if (!letters.Contains(read))
{
Console.WriteLine("You have entered an incorrect value");
continue;
}
var found = false;
for (int i = 0; i < count; i++)
{
if (array[i] == read)
{
found = true;
}
}
if (found)
{
Console.WriteLine("You have entered an duplicate value");
continue;
}
array[count++] = read;
}
Console.WriteLine("You have Entered the following Inputs: ");
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(array[i]);
}
Console.ReadKey();
this is you problem
for (int i = 0; i < 5; i++)
this is your fix:
static void Main(string[] args)
{
char[] Array = new char[5];
Console.WriteLine("Please Enter 5 Letters B/W a through j only: ");
string letters = "abcdefghij";
char[] read = Console.ReadLine().ToLower().ToCharArray();
//loop through array
for (int i = 0; i < read.Length; i++)
{
if (letters.Contains(read[i]) && !Array.Contains(read[i]))
{
Array[i] = read[i];
}
else
{
Console.WriteLine("You have entered an incorrect value");
}
}
Console.WriteLine("You have Entered the following Inputs: ");
for (int i = 0; i < Array.Length; i++)
{
Console.WriteLine(Array[i]);
}
Console.ReadKey();
}