What I am looking for is how to read an integer that was given by the user from the command line (console project). I primarily know C++ and have started down the C# path. I
Try this it will not throw exception and user can try again:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice = 0;
while (!Int32.TryParse(Console.ReadLine(), out choice))
{
Console.WriteLine("Wrong input! Enter choice number again:");
}
You could just go ahead and try :
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice=int.Parse(Console.ReadLine());
That should work for the case statement.
It works with the switch statement and doesn't throw an exception.
I used int intTemp = Convert.ToInt32(Console.ReadLine());
and it worked well, here's my example:
int balance = 10000;
int retrieve = 0;
Console.Write("Hello, write the amount you want to retrieve: ");
retrieve = Convert.ToInt32(Console.ReadLine());
You need to typecast the input. try using the following
int input = Convert.ToInt32(Console.ReadLine());
It will throw exception if the value is non-numeric.
I understand that the above is a quick one. I would like to improve my answer:
String input = Console.ReadLine();
int selectedOption;
if(int.TryParse(input, out selectedOption))
{
switch(selectedOption)
{
case 1:
//your code here.
break;
case 2:
//another one.
break;
//. and so on, default..
}
}
else
{
//print error indicating non-numeric input is unsupported or something more meaningful.
}
You can convert the string to integer using Convert.ToInt32() function
int intTemp = Convert.ToInt32(Console.ReadLine());
Better way is to use TryParse:
Int32 _userInput;
if(Int32.TryParse (Console.Readline(), out _userInput) {// do the stuff on userInput}