This question already has answers here:
How to validate user input for whether it's an integer?
(10 answers)
Closed 4 years ago.
So i nearly have 2k lines of code and i have forgotten to / i do not know how to have input valdation on user inputs such as
cw("Hello Please Enter your age");
cw("If you are in a Group Input the Age of the Youngest Member of the Group.");
Age = Convert.ToInt32(Console.ReadLine());
I want to Make it so that users can enter only numbers and my program will not crash when they put in somthing els.
this is a common problem in the whole of my program for the console.readlines.
Is there a way on mass that i can introduce the input valdation for numbers only and letters only when approate?
thank you in advance.
This is what I'd do (after a little more polish):
public static bool PromptForInt(string promptString, out int result, string helpString = null)
{
while (true)
{
Console.WriteLine(promptString);
var response = Console.ReadLine();
if (string.Equals(response, "Q", StringComparison.OrdinalIgnoreCase))
{
result = 0;
return false;
}
if (helpString != null && string.Equals(response, "H", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine(helpString);
continue; //skip back to the top of the loop
}
if (int.TryParse(response, out result))
{
return true;
}
}
}
You could right similar functions for other types (for example, double or DateTime, always using typeName.TryParse.
In terms of polishing, you might want to have a useful error message if the user doesn't enter "Q", "H" or a valid int. Otherwise...
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
The community is reviewing whether to reopen this question as of 2 years ago.
Improve this question
I cooked this up and was wondering if there is a better way to do this.
```Console.WriteLine("Name me.");
String cn = Console.ReadLine();
Console.WriteLine($"I like this name ,{cn}, What is my funcion? ");
String fn = Console.ReadLine();
Console.WriteLine($"I will learn how to do {fn} for you.");
Console.WriteLine("I Will double any number you give me.");
int a = Convert.ToInt32(Console.ReadLine());
int b = 2;
Console.WriteLine(a * b);
```
"Best" is subjective, but there are a few problems with the code:
Any non-number string entered will throw an exception
Any decimal number string will also throw an exception.
Instead of using Convert.ToInt32, you should consider using the TryParse method instead. This method takes in a string and an out parameter that gets set to the converted value if it's successful (otherwise 0), and it returns a bool that indicates success. If we use the decimal type, we will end up with a number that has very good precision and can include decimals.
If we then create a method with a loop that uses the result of TryParse as a condition, we can loop until the user enters a correct number.
We could also allow the user to pass in a validation method, so that they can specify what the rules are for a "valid" number (i.e. if it must be greater than zero, or must be odd, etc.).
Then we might end up with something like this:
public static decimal GetDecimalFromUser(string prompt,
Func<decimal, bool> validator = null)
{
bool isValid = true;
decimal result;
do
{
if (!isValid)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Invalid input, please try again.");
Console.ResetColor();
}
else isValid = false;
Console.Write(prompt);
} while (!decimal.TryParse(Console.ReadLine(), out result) &&
(validator == null || !validator.Invoke(result)));
return result;
}
Similarly, we can write code that prompts the user for string input. This will save us a few lines of code in our Main method, because we don't have to keep writing Console.WriteLine and Console.ReadLine:
public static string GetStringFromUser(string prompt)
{
Console.Write(prompt);
return Console.ReadLine();
}
Now we can write code where the user cannot enter invalid input! In use, the code would then look like:
string name = GetStringFromUser("Please give me a name: ");
string fn = GetStringFromUser($"I like this name, {name}. What is my function? ");
Console.WriteLine($"I will learn how to do {fn} for you.");
decimal input = GetDecimalFromUser("Please enter a number and I will double it: ");
Console.WriteLine($"{input} * 2 = {input * 2}");
This question already has answers here:
Convert String to int in C#
(5 answers)
Closed 4 years ago.
I have been learning the basics of C# with a Console Application. I was wondering if anyone knew how to use an IF statement with a String instead of an integer. It's a bit annoying and I need it so I can compare a value the user has outputted to the console. This is because the Console.ReadLine(); only likes Strings and not Integers. Below is my code:
string num = Console.ReadLine();
if (num == 9)
{
Console.WriteLine("Ooh my number is 9");
}
Any help is appreciated!
You should always validate integer user input with TryParse
int.TryParse
Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the operation
succeeded.
string value = Console.ReadLine();
if(!int.TryParse(value, out var num))
{
Console.WriteLine("You had one job!");
}
else if (num == 9)
{
Console.WriteLine("Ooh my number is 9");
}
This question already has answers here:
C# How to loop user input until the datatype of the input is correct?
(4 answers)
Closed 6 years ago.
I trying to solve this code so it repeats exception until input is a number. right now it stop right first attempt and I do know how to place while loop.
int nomer2;
WriteLine("Write Number");
try
{
nomer2 = Convert.ToInt32(ReadLine());
WriteLine("here is my Number {0}", nomer2);
}
catch (Exception)
{
WriteLine("Error: Enter Number");
}
Its recommended not to use exceptions unless it is really unexpected what the result would be. You can use the TryParse function which tries to convert the string that is passed to it to an integer. If the conversion was successful, the integer is returned by reference in the second param and the function returns true, otherwise, it returns false.
int nomer2;
string input = string.Empty;
do
{
Console.WriteLine("Write Number");
input = Console.ReadLine();
}
while (!int.TryParse(input, out nomer2)) ;
Console.WriteLine("here is my Number {0}", nomer2);
while(!int.TryParse(ReadLine(), out nomer2))
{
WriteLine("Write Number");
}
WriteLine("here is my Number {0}", nomer2);
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();
I am currently working on a program and I am finalising it by going over with error handling. I have several cases which look like:
int stockbankInput = Convert.ToInt32(Console.ReadLine());
Here, the user must enter either 1, 2, 3. I have tried to use an if statement to catch the error if anybody inputs a blankspace/string/character or a number that is not 1,2 or 3 but it doesn't work in the same sense as a string input. Below is what I have tried:
if(stockbankInput == null)
{
Console.WriteLine("Error: Please enter either 1, 2 or 3");
stockbankInput = 0;
goto menuRestartLine;
}
However, you cannot link 'null' with an integer input, only a string. Can anybody help with this please?
Use the Int32 TryParse method:
int input;
var successful = Int32.TryParse(Console.ReadLine(), out input);
if (!successful)
// do something else
else
return input;
You're checking if an int is null, which will always return false because an int cannot be null.
You can use 'int?' (Nullable int) but Convert.ToInt32 will not return null. If the value of the int cannot be resolved it will resolve to the default value of zero. You can either check if the returned int is zero or do some further checking of the returned string:
int input = 0;
string errorMessage = "Error: Please enter either 1, 2 or 3";
while(true)
{
try
{
input = Convert.ToInt32(Console.ReadLine());
if (input == 0 || input > 3)
{
Console.WriteLine(errorMessage);
}
else
{
break;
}
}
catch(FormatException)
{
Console.WriteLine(errorMessage);
}
}
With this you your returned value "int input" will either be 0 or the number you entered and FormatExceptions caused by the string to convert containing symbols other than the digits 0-9 will be caught in the try/catch statement.
give this sample program a try:
static void Main(string[] args)
{
int stockbankInput = 0;
bool firstTry = true;
while(stockbankInput < 1 | stockbankInput > 3)
{
if(!firstTry)
Console.WriteLine("Error: Please enter either 1, 2 or 3");
firstTry = false;
Int32.TryParse(Console.ReadLine(), out stockbankInput);
}
}
First of all, don't use goto statements. They are considered bad practice, and it's like a blinding red light when reading your question - that's all I can focus on.
As per your question, an int or Int32 cannot be null. So you can't compare it to null. Give it a default value, and then check that.
This is a scenario where you don't need to check for an error, but just need to validate input. Use TryParse, which will set your out parameter if the parse is successful, or else set it to 0.
Next, you want to loop until you are given good input. An if statement is executed once, a loop will guarantee that when you leave it, your input will be valid.
Lastly, the firstTry is just a nice way to let the user know, after their first try, that they screwed up.