Number Value Input Exception [duplicate] - c#

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

Related

How to print an error message if input is not a number?

I wonder how to print an error message if user's input is not a number.
Console.WriteLine("Water amount in ml:");
int waterAmount = Convert.ToInt32(Console.ReadLine());
Most answers from other posts don't work, because waterAmount is a Int32, not a string.
Also, sorry if my English is weak, it's not my native language
I see you did not accept the other answers. Maybe you want to make the user try again after he did not input a number. You can do that with a while loop, or easier, using the goto keyword. You simply put a tag before everything is happening (in my case, waterAmountInput), and if the input was not a number, you write your error message and go to the beginning again. Here is the code:
int waterAmount;
waterAmountInput:
Console.Write("Water amount in ml: ");
try
{
waterAmount = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("The water amount needs to be a number!");
goto waterAmountInput;
}
You can try using C#'s TryParse() functions.
These attempt to convert values, but if they fail they return false rather than erroring.
I would suggest trying this code:
Console.WriteLine("Water amount in ml:");
string input = Console.ReadLine();
if (Int32.TryParse(input, out var value))
// Do something here. The converted int is stored in "value".
else
Console.WriteLine("Please enter a number");
You should use TryParse function:
Console.WriteLine("Water amount in ml:");
int waterAmount = 0;
if (int.TryParse(Console.ReadLine(), waterAmount)) {
} else {
Console.WriteLine("Error Message");
}
You will need to use TryParse before presuming it to be a number.
After Console.WriteLine you can capture and parse the input and if TryParse returns false, you can display an error message.
Note: if the conversion succeeds the numeric value is available in the waterAmt local variable.
Console.WriteLine("Water amount in ml:");
var input = Console.ReadLine();
if(!int.TryParse(input, out int waterAmt))
Console.WriteLine("Input is not a number");

Input validation with integer and int.tryparse [duplicate]

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

How to use a String instead of an Interger with an IF statement in a C# Console program? [duplicate]

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

ToInt32 throwing weird results [duplicate]

This question already has answers here:
Input string was not in a correct format
(9 answers)
Closed 5 years ago.
Well, i've been having a problem with the code of a memory game. It is like a simon says but with numbers in C#.
The problem comes when, in the code, i use the Console Readkey to let the player make an input. But, the problem comes when i convert to int a number... It takes it like i had put a value that mismatched the type of data. Why does that happen=
public void playersTurn() {
for (int i = 0; i < 6; i++) {
if (!(failure)){
playerInput = Console.ReadKey().Key.ToString(); // if i put, for example, 5
Console.Write(playerInput); // it throws 5D50 (this was just to see if something weird was happening)
try{
playerNumber = Convert.ToInt32(playerInput);
}
catch(FormatException e){
Console.Clear();
Console.WriteLine("Solo numeros, chico"); // there is always an exception
}
Console.Write(playerNumber + " ");
if (playerNumber != thoseNumbers[i]) {
Console.WriteLine(" ");
Console.WriteLine("¡ERROR!");
failure = true;
}
}
thoseNumbers[i] = 0;
}
The convert method throws exception because it expects a number. If you pass it a string like 5D50 it will not know what to do with 'D' so it will throw exception.
Readkey() returns code of key, not the value the key is used for. Try this:
Convert.ToInt32(Console.Readline());

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

Categories