I\'m asking the user to input 5 numbers and store it into an array so I can send the values in a method and subtract 5 numbers from each array. When I use the:
furkle is correct, it's not working because the console.ReadLine method returns a string, and you can't assign a string to an int array. However, the solution provided is a bit clunky because it only reads one character at a time from the console. It's better to take in all the input at once.
Here is a short console program that
Error handling is included.
static void Main(string[] args){
var intList = new List();
string sUserInput = "";
var sList = new List();
bool validInput = true;
do
{
validInput = true;
Console.WriteLine("input a space separated list of integers");
sUserInput = Console.ReadLine();
sList = sUserInput.Split(' ').ToList();
try
{
foreach (var item in sList) {intList.Add(int.Parse(item));}
}
catch (Exception e)
{
validInput = false;
Console.WriteLine("An error occurred. You may have entered the list incorrectly. Please make sure you only enter integer values separated by a space. \r\n");
}
} while (validInput == false);
Console.WriteLine("\r\nHere are the contents of the intList:");
foreach (var item in intList)
{
Console.WriteLine(item);
}
Console.WriteLine("\r\npress any key to exit...");
Console.ReadKey();
}//end main
If you want to make sure the user only enters a total of 5 integers you can do the DO WHILE loop like this:
do
{
validInput = true;
Console.WriteLine("input a space separated list of integers");
sUserInput = Console.ReadLine();
sList = sUserInput.Split(' ').ToList();
if (sList.Count > 5)
{
validInput = false;
Console.WriteLine("you entered too many integers. You must enter only 5 integers. \r\n");
}
else
{
try
{
foreach (var item in sList) { intList.Add(int.Parse(item)); }
}
catch (Exception e)
{
validInput = false;
Console.WriteLine("An error occurred. You may have entered the list incorrectly. Please make sure you only enter integer values separated by a space. \r\n");
}
}
} while (validInput == false);