Reading an integer from user input - c#

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 know that Console.ReadLine(); only takes a char/string. So in short I am looking for the integer version of this.
Just to give you an idea of what I'm doing exactly:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
Console.ReadLine(); // Needs to take in int rather than string or char.
I have been looking for quite a while for this. I have found a lot on C but not C#. I did find however a thread, on another site, that suggested to convert from char to int. I'm sure there has to be a more direct way than converting.

You can convert the string to integer using Convert.ToInt32() function
int intTemp = Convert.ToInt32(Console.ReadLine());

I would suggest you use TryParse:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
string input = Console.ReadLine();
int number;
Int32.TryParse(input, out number);
This way, your application does not throw an exception, if you try to parse something like "1q" or "23e", because somebody made a faulty input.
Int32.TryParse returns a boolean value, so you can use it in an if statement, to see whether or not you need to branch of your code:
int number;
if(!Int32.TryParse(input, out number))
{
//no, not able to parse, repeat, throw exception, use fallback value?
}
To your question: You will not find a solution to read an integer because ReadLine() reads the whole command line, threfor returns a string. What you can do is, try to convert this input into and int16/32/64 variable.
There are several methods for this:
Int.Parse()
Convert.ToInt()
Int.TryParse()
If you are in doubt about the input, which is to be converted, always go for the TryParse methods, no matter if you try to parse strings, int variable or what not.
Update
In C# 7.0 out variables can be declared directly where they are passed in as an argument, so the above code could be condensed into this:
if(Int32.TryParse(input, out int number))
{
/* Yes input could be parsed and we can now use number in this code block
scope */
}
else
{
/* No, input could not be parsed to an integer */
}
A complete example would look like this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var foo = Console.ReadLine();
if (int.TryParse(foo, out int number1)) {
Console.WriteLine($"{number1} is a number");
}
else
{
Console.WriteLine($"{foo} is not a number");
}
Console.WriteLine($"The value of the variable {nameof(number1)} is {number1}");
Console.ReadLine();
}
}
Here you can see, that the variable number1 does get initialized even if the input is not a number and has the value 0 regardless, so it is valid even outside the declaring if block

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.
Edit
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.
}

int op = 0;
string in = string.Empty;
do
{
Console.WriteLine("enter choice");
in = Console.ReadLine();
} while (!int.TryParse(in, out op));

Use this simple line:
int x = int.Parse(Console.ReadLine());

I didn't see a good and complete answer to your question, so I will show a more complete example. There are some methods posted showing how to get integer input from the user, but whenever you do this you usually also need to
validate the input
display an error message if invalid input
is given, and
loop through until a valid input is given.
This example shows how to get an integer value from the user that is equal to or greater than 1. If invalid input is given, it will catch the error, display an error message, and request the user to try again for a correct input.
static void Main(string[] args)
{
int intUserInput = 0;
bool validUserInput = false;
while (validUserInput == false)
{
try
{
Console.Write("Please enter an integer value greater than or equal to 1: ");
intUserInput = int.Parse(Console.ReadLine()); //try to parse the user input to an int variable
}
catch (Exception e) //catch exception for invalid input, such as a letter
{
Console.WriteLine(e.Message);
}
if (intUserInput >= 1) { validUserInput = true; }
else { Console.WriteLine(intUserInput + " is not a valid input, please enter an integer greater than 0."); }
} //end while
Console.WriteLine("You entered " + intUserInput);
Console.WriteLine("Press any key to exit ");
Console.ReadKey();
} //end main
In your question it looks like you wanted to use this for menu options. So if you wanted to get int input for choosing a menu option you could change the if statement to
if ( (intUserInput >= 1) && (intUserInput <= 4) )
This would work if you needed the user to pick an option of 1, 2, 3, or 4.

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());

Better way is to use TryParse:
Int32 _userInput;
if(Int32.TryParse (Console.Readline(), out _userInput) {// do the stuff on userInput}

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:");
}

static void Main(string[] args)
{
Console.WriteLine("Please enter a number from 1 to 10");
int counter = Convert.ToInt32(Console.ReadLine());
//Here is your variable
Console.WriteLine("The numbers start from");
do
{
counter++;
Console.Write(counter + ", ");
} while (counter < 100);
Console.ReadKey();
}

You could create your own ReadInt function, that only allows numbers
(this function is probably not the best way to go about this, but does the job)
public static int ReadInt()
{
string allowedChars = "0123456789";
ConsoleKeyInfo read = new ConsoleKeyInfo();
List<char> outInt = new List<char>();
while(!(read.Key == ConsoleKey.Enter && outInt.Count > 0))
{
read = Console.ReadKey(true);
if (allowedChars.Contains(read.KeyChar.ToString()))
{
outInt.Add(read.KeyChar);
Console.Write(read.KeyChar.ToString());
}
if(read.Key == ConsoleKey.Backspace)
{
if(outInt.Count > 0)
{
outInt.RemoveAt(outInt.Count - 1);
Console.CursorLeft--;
Console.Write(" ");
Console.CursorLeft--;
}
}
}
Console.SetCursorPosition(0, Console.CursorTop + 1);
return int.Parse(new string(outInt.ToArray()));
}

Declare a variable that will contain the value of the user input :
Ex :
int userInput = Convert.ToInt32(Console.ReadLine());

I know this question is old, but with some newer C# features like lambda expressions, here's what I actually implemented for my project today:
private static async Task Main()
{
// -- More of my code here
Console.WriteLine("1. Add account.");
Console.WriteLine("2. View accounts.");
int choice = ReadInt("Please enter your choice: ");
// -- Code that uses the choice variable
}
// I have this as a public function in a utility class,
// but you could use it directly in Program.cs
private static int ReadInt(string prompt)
{
string? text;
do
{
Console.Write(prompt);
text = Console.ReadLine();
} while (text == null || !text.Where(c => char.IsNumber(c)).Any());
return int.Parse(new string(text.Where(c => char.IsNumber(c)).ToArray()));
}
The difference here is that if you accidentally type a number and any other text along with that number, only the number is parsed.

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.

Related

is there a way to instead of making double not freeze project and instead say invalid number?

i am new in stack overflow, but i've ran into a problem.
what i want to do exactly is an advanced calculator, but can't find out a way to give an error message (then i will add a retry option) instead of making the console freeze.
Console.Write("Type A Number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
//detects numbers
if (num1 != "1")
Console.WriteLine("invalid number!");
//detects numbers
Console.Write("Type An Operator: ");
string op = Console.ReadLine();
Console.Write("Type Another Number: ");
double num2 = Convert.ToDouble(Console.ReadLine());
//the operator logic system!!!
the operator logic system detects if the operator (+ - x/* / etc) is valid, but I can't find out for number. after that, I am going to make a game, but I can't find out for this one now.
Try this:
Console.Write("Type A Number: ");
if (!double.TryParse (Console.ReadLine(), out double num1))
Console.WriteLine("invalid number!");
TryParse returns false if the entered text is not a valid double. If it is valid it returns true and puts the number into num1.
This code is going to cause you issues if the user enters an unexpected value. E.g. They enter a string instead of a number. So you need to also look for and account for that.
Best is to create different methods which will check the input and only return a valid result, otherwise to prompt the user. So you have something like this;
The main method calls submethods, so is relatively simple.
You call GetValidNumber to return the number inputs for bother number 1 and number 2
GetValidOperator to return the valid operator, which itself calls IsValidOperator to check the input is valid (as there is more to check).
Double.TryParse(...) is the main check if the double number entered is valid or not. But using TryParese it will not through an exception if the user enters an non-valid number, but rather just return false. So it is a safe way of checking user input in this case.
The code might need refining and error checking improved, but it should put you on the right course.
static void Main(string[] args)
{
double number1 = GetValidNumber("Enter first number");
string op = GetValidOperator();
double number2 = GetValidNumber("Enter second number");
Console.WriteLine($"Operation is {number1} {op} {number2}");
//Add code to perform your operation
}
private static double GetValidNumber(string message)
{
Console.WriteLine(message);
string input = Console.ReadLine();
double output;
while (!Double.TryParse(input, out output) )
{
Console.WriteLine("Invalid number! Please try again");
input = Console.ReadLine();
}
return output;
}
private static string GetValidOperator()
{
Console.WriteLine("Enter an operator + - * / ");
string input = Console.ReadLine();
while (!IsValidOperator(input))
{
Console.WriteLine("Invalid Operator! Please try again");
input = Console.ReadLine();
}
return input;
}
private static bool IsValidOperator(string input)
{
bool result = false;
if (String.IsNullOrWhiteSpace(input))
return false;
if (input.Length != 1)
return false;
if (input[0] == '+' || input[0] == '-' || input[0] == '/' || input[0] == '*')
return true;
else
return result;
}
Well, you can use Double.Parse instead of Convert.ToDouble. It will throw exception on failed conversion and you will be able to handle that.

C# returning a completely unrelated and seemingly random integer?

I am currently a complete beginner to C# however I am having this issue and as a python user the error doesn't make any sense to me. I have tried to find a fix but I don't know what to search for or how to describe the error, so please help!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace testin
{
class Program
{
static void Main(string[] args)
{
PrintState();
CalculateAge();
EzMaths();
//Here I call the procedure which is declared later on
Console.ReadLine();
}
static void PrintState()
{
/*Here I write the procedure of 'PrintState',
* or print statement. The program will print "hey world"
* to the console as a result. */
Console.WriteLine("Hey world");
}
static void EzMaths()
{
Console.WriteLine("Enter the first number ");
Console.Write("> ");
int num1 = Console.Read();
Console.WriteLine("Enter the second number ");
Console.Write("> ");
int num2 = Console.Read();
int total = (num1 + num2);
Console.WriteLine(total);
}
static void CalculateAge()
{
Console.WriteLine("Enter your year of birth ");
Console.Write("> ");
int date = Console.Read();
int age = (2018 - date);
Console.Write("You are " + (age));
Console.ReadLine();
}
}
}
Console.Read(); does read the next Character, but as its int representation. You'll need to use Console.ReadLine();, but now you're faced with a different problem, Console.ReadLine(); returns a string and not a int, so now you need to Convert it. In the .NET World you'd do it like this:
string userInput = Console.ReadLine();
int userInputNumber = Convert.ToInt32(userInput);
This is not safe, as the user could enter something that's not a number and that would make the program crash. Of course if you're just getting started and making a "Hello World" application this is probably not your biggest concern.
I'll post the better version anyways if yo're interested:
string userInput = Console.ReadLine();
int userInputNumber;
if (int.TryParse(userInput, out userInputNumber))
{
// Do code here with userInputNumber as your number
}
And in C# (like every modern Language) we have some Syntatic Sugar to make this shorter but also harder to read:
if (int.TryParse(Console.ReadLine(), out int userInputNumber))
{
//Do code here
}
you need to use console.ReadLine() instead of console.Read() in your CalculateAge function.
refer to this answer to understand the difference between Console.Read and console.ReadLine:
Difference between Console.Read() and Console.ReadLine()?
Yet I would suggest that you also add a tryParse in order to validate if the entered value is an integer before you convert it to int
something like this:
static void CalculateAge()
{
Console.WriteLine("Enter your year of birth ");
Console.Write("> ");
string input = Console.ReadLine();
int date = 2018;
Int32.TryParse(input, out date);
int age = (2018 - date);
Console.Write("You are " + (age));
Console.ReadLine();
}
you can have another implementation if you dont want it to have a default value of 2018. like add a while loop, while tryParse != false then keep asking for input.

C# read value from user console.read [duplicate]

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 know that Console.ReadLine(); only takes a char/string. So in short I am looking for the integer version of this.
Just to give you an idea of what I'm doing exactly:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
Console.ReadLine(); // Needs to take in int rather than string or char.
I have been looking for quite a while for this. I have found a lot on C but not C#. I did find however a thread, on another site, that suggested to convert from char to int. I'm sure there has to be a more direct way than converting.
You can convert the string to integer using Convert.ToInt32() function
int intTemp = Convert.ToInt32(Console.ReadLine());
I would suggest you use TryParse:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
string input = Console.ReadLine();
int number;
Int32.TryParse(input, out number);
This way, your application does not throw an exception, if you try to parse something like "1q" or "23e", because somebody made a faulty input.
Int32.TryParse returns a boolean value, so you can use it in an if statement, to see whether or not you need to branch of your code:
int number;
if(!Int32.TryParse(input, out number))
{
//no, not able to parse, repeat, throw exception, use fallback value?
}
To your question: You will not find a solution to read an integer because ReadLine() reads the whole command line, threfor returns a string. What you can do is, try to convert this input into and int16/32/64 variable.
There are several methods for this:
Int.Parse()
Convert.ToInt()
Int.TryParse()
If you are in doubt about the input, which is to be converted, always go for the TryParse methods, no matter if you try to parse strings, int variable or what not.
Update
In C# 7.0 out variables can be declared directly where they are passed in as an argument, so the above code could be condensed into this:
if(Int32.TryParse(input, out int number))
{
/* Yes input could be parsed and we can now use number in this code block
scope */
}
else
{
/* No, input could not be parsed to an integer */
}
A complete example would look like this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var foo = Console.ReadLine();
if (int.TryParse(foo, out int number1)) {
Console.WriteLine($"{number1} is a number");
}
else
{
Console.WriteLine($"{foo} is not a number");
}
Console.WriteLine($"The value of the variable {nameof(number1)} is {number1}");
Console.ReadLine();
}
}
Here you can see, that the variable number1 does get initialized even if the input is not a number and has the value 0 regardless, so it is valid even outside the declaring if block
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.
Edit
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.
}
int op = 0;
string in = string.Empty;
do
{
Console.WriteLine("enter choice");
in = Console.ReadLine();
} while (!int.TryParse(in, out op));
Use this simple line:
int x = int.Parse(Console.ReadLine());
I didn't see a good and complete answer to your question, so I will show a more complete example. There are some methods posted showing how to get integer input from the user, but whenever you do this you usually also need to
validate the input
display an error message if invalid input
is given, and
loop through until a valid input is given.
This example shows how to get an integer value from the user that is equal to or greater than 1. If invalid input is given, it will catch the error, display an error message, and request the user to try again for a correct input.
static void Main(string[] args)
{
int intUserInput = 0;
bool validUserInput = false;
while (validUserInput == false)
{
try
{
Console.Write("Please enter an integer value greater than or equal to 1: ");
intUserInput = int.Parse(Console.ReadLine()); //try to parse the user input to an int variable
}
catch (Exception e) //catch exception for invalid input, such as a letter
{
Console.WriteLine(e.Message);
}
if (intUserInput >= 1) { validUserInput = true; }
else { Console.WriteLine(intUserInput + " is not a valid input, please enter an integer greater than 0."); }
} //end while
Console.WriteLine("You entered " + intUserInput);
Console.WriteLine("Press any key to exit ");
Console.ReadKey();
} //end main
In your question it looks like you wanted to use this for menu options. So if you wanted to get int input for choosing a menu option you could change the if statement to
if ( (intUserInput >= 1) && (intUserInput <= 4) )
This would work if you needed the user to pick an option of 1, 2, 3, or 4.
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());
Better way is to use TryParse:
Int32 _userInput;
if(Int32.TryParse (Console.Readline(), out _userInput) {// do the stuff on userInput}
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:");
}
static void Main(string[] args)
{
Console.WriteLine("Please enter a number from 1 to 10");
int counter = Convert.ToInt32(Console.ReadLine());
//Here is your variable
Console.WriteLine("The numbers start from");
do
{
counter++;
Console.Write(counter + ", ");
} while (counter < 100);
Console.ReadKey();
}
You could create your own ReadInt function, that only allows numbers
(this function is probably not the best way to go about this, but does the job)
public static int ReadInt()
{
string allowedChars = "0123456789";
ConsoleKeyInfo read = new ConsoleKeyInfo();
List<char> outInt = new List<char>();
while(!(read.Key == ConsoleKey.Enter && outInt.Count > 0))
{
read = Console.ReadKey(true);
if (allowedChars.Contains(read.KeyChar.ToString()))
{
outInt.Add(read.KeyChar);
Console.Write(read.KeyChar.ToString());
}
if(read.Key == ConsoleKey.Backspace)
{
if(outInt.Count > 0)
{
outInt.RemoveAt(outInt.Count - 1);
Console.CursorLeft--;
Console.Write(" ");
Console.CursorLeft--;
}
}
}
Console.SetCursorPosition(0, Console.CursorTop + 1);
return int.Parse(new string(outInt.ToArray()));
}
Declare a variable that will contain the value of the user input :
Ex :
int userInput = Convert.ToInt32(Console.ReadLine());
I know this question is old, but with some newer C# features like lambda expressions, here's what I actually implemented for my project today:
private static async Task Main()
{
// -- More of my code here
Console.WriteLine("1. Add account.");
Console.WriteLine("2. View accounts.");
int choice = ReadInt("Please enter your choice: ");
// -- Code that uses the choice variable
}
// I have this as a public function in a utility class,
// but you could use it directly in Program.cs
private static int ReadInt(string prompt)
{
string? text;
do
{
Console.Write(prompt);
text = Console.ReadLine();
} while (text == null || !text.Where(c => char.IsNumber(c)).Any());
return int.Parse(new string(text.Where(c => char.IsNumber(c)).ToArray()));
}
The difference here is that if you accidentally type a number and any other text along with that number, only the number is parsed.
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.

How do I make a loop that prompts the user to enter data every time they enter an invalid data type? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Console.WriteLine("Enter value for Monday : ");
milesMon = Console.ReadLine();
try
{
dblMon = double.Parse(milesMon);
}
catch
{
Console.WriteLine("You entered an invalid number - a default of 0 has been set");
dblMon = 0;
while (true) break;
Console.WriteLine("Enter value for Monday : ");
milesMon = Console.ReadLine();
In it's current state the code only prompts the user after they enter incorrect data the first time they do it, I would like to know how to make it so it happens every time.
-Thanks
You should use a do or while loop to keep repeating the prompt until a valid double is entered. You should also consider adding some form of exit keywords. Like if they enter "exit, quit, q" etc.. Have it terminate the app instead of loop back around. However being a console app, ctrl + c will close it regardless of what it's doing (it's the kill command) but not everyone knows that.
bool repeat = true;
var dblMilesMon = (double)0;
do
{
Console.WriteLine("Enter value for Monday : ");
var strMilesMon = Console.ReadLine();
if (!double.TryParse(strMilesMon, out dblMilesMon))
Console.WriteLine("You entered an invalid number - please enter a numeric value.")
else
repeat = false;
}while (repeat);
//do something with dblMilesMon
You can use TryParse() to convert the input string to double, it will return false if the conversion failed; based on that input you can prompt the user that whether the input is valid or not. and this will loop until the user enter Exit
string inputVal = "";
double inputDoubleVal;
while (inputVal == "Exit")
{
Console.WriteLine("Enter value for Monday : ");
inputVal = Console.ReadLine();
if (double.TryParse(inputVal, out inputDoubleVal))
{
//Process with your double value
}
else
{
Console.WriteLine("You entered an invalid number - a default of 0 has been set");
}
}
Basically you want to write a loop. While the input is invalid, prompt the user. So you should have a bool variable called valid to indicate whether the input is valid. And than a while loop like this:
while (!valid) {
//...
}
In the while loop, prompt the user. So the code looks like this:
bool valid = false;
int input = 0;
while (!valid) {
Console.WriteLine ("Prompt");
try
{
input = Convert.ToInt32 (Console.ReadLine ());
valid = true;
}
catch {}
}
Hope this helps!
You can use recursion to create your end-less loop without using a for or while.
Also, instead of a try-catch statement, better use a TryParse
Doc ref: https://msdn.microsoft.com/en-us/library/bb384043.aspx
public int readInput(){
int val = 0;
Console.WriteLine("Enter a valid int");
string enteredVal = Console.ReadLine();
bool result = int.TryParse(enteredVal, out val);
if(result)
return val;
Console.writeLine("Try again, only int values allowed");
return readInput();
}
int val = readInput();

C# How to loop user input until the datatype of the input is correct?

How to make this piece of code loop asking for input from the user until int.TryParse()
is successful?
//setX
public void setX()
{
//take the input from the user
string temp;
int temp2;
System.Console.WriteLine("Enter a value for X:");
temp = System.Console.ReadLine();
if (int.TryParse(temp, out temp2))
x = temp2;
else
System.Console.WriteLine("You must enter an integer type value"); 'need to make it ask user for another input if first one was of invalid type'
}
Version of the code after the helpful answer:
//setX
public void setX()
{
//take the input from the user
string temp;
int temp2;
System.Console.WriteLine("Enter a value for X:");
temp = System.Console.ReadLine();
if (int.TryParse(temp, out temp2))
x = temp2;
else
{
Console.WriteLine("The value must be of integer type");
while (!int.TryParse(Console.ReadLine(), out temp2))
Console.WriteLine("The value must be of integer type");
x = temp2;
}
}
while (!int.TryParse(Console.ReadLine(), out mynum))
Console.WriteLine("Try again");
edit:
public void setX() {
Console.Write("Enter a value for X (int): ");
while (!int.TryParse(Console.ReadLine(), out x))
Console.Write("The value must be of integer type, try again: ");
}
Try this. I personally prefer to use while, but do .. while is also valid solution. The thing is that I don't really want to print error message before any input. However while has also problem with more complicated input that can't be pushed into one line. It really depends on what exactly you need. In some cases I'd even recommend to use goto even tho some people would probably track me down and slap me with a fish because of it.
Even though the question has been already marked as answered, do-while loops are much better for validating user input.
Notice your code:
Console.WriteLine("The value must be of integer type");
while (!int.TryParse(Console.ReadLine(), out temp2))
Console.WriteLine("The value must be of integer type");
You have the same code at top and bottom. This can be changed:
do {
Console.WriteLine("The value must be of integer type");
} while (!int.TryParse(Console.ReadLine(), out temp2));
This can help too
public int fun()
{
int Choice=0;
try
{
Choice = int.Parse(Console.ReadLine());
return choice;
}
catch (Exception)
{
return fun();
}
}
I've been wondering quite a lot, but I just figured it out!
int number;
bool check;
do
{
Console.WriteLine("Enter an integer:");
check = int.TryParse(Console.ReadLine(), out num1);
}
while (!check);
This code will loop until the user has entered an integer number. This way, the program doesn't simply report an error, but instead immediately allows the user to input again another, correct value.

Categories