Checking if user input is a letter [duplicate] - c#

This question already has answers here:
Identify if a string is a number
(26 answers)
Closed 5 years ago.
I'm receiving some user input through a TextBox which is then being converted to an int so it can be used in further calculations when I click the Calculate button.
I have checked to see if the TextBox is empty when the Calculate button is clicked, if it is, then a message box appears. Now I realised I need to check to make sure it is a number being input, not a letter. I'm looking for something similar to this
if(hoursInput.Text == "" || hoursInput.Text contains "a-z")
{
\\ handle error
}
else
{
\\ continue with code
}
EDIT:
The user input is converted to an int in the else block, but I do not want the function to reach this stage of converting from string to int if the user input contains letters, which is why I want to check to see if the user input contains any letters in the if block

As mentioned, use Int32.TryParse which will return a bool of whether or not the input could be parsed to an Int32. One of the parameters is an out and will become the Int32 if the input could be parsed.
See:
https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx
if(hoursInput.Text == "" || !Int32.TryParse(hoursInput.Text, out number))
{
\\ handle error
}
else
{
\\ continue with code
}

You really don't need to check anything explicitly:
int aNumber;
if (!Int32.TryParse(hoursInput.Text, out aNumber)) {
// handle error
} else {
// handle `aNumber`
}

Related

Why is my code outputting strings multiple times in my if statement?

My code outputs the same string multiple times. For example, typing in 40 results in "Nope! Your answer is too high. Try again." twice, and it displays "your answer is too low" twice.
while (numberguess != 40.5)
{
numberguess = Console.Read();
if (numberguess < 40.5)
{
Console.WriteLine("Nope! Your answer is too low. Try again.");
}
else if (numberguess > 40.5)
{
Console.WriteLine("Nope! Your answer is too high. Try again.");
}
else if (numberguess == 40.5)
{
Console.WriteLine("Correct! Wow, I didn't really think you would figure it out!");
break;
}
}
I expect only one string to show up when typing in a number, and I want it to correspond to whether it is lower or higher than a particular number.
There are several problems with this single line:
numberguess = Console.Read();
First this returns an int, so it will never return 40.5. Also this reads one character at a time, including the ones input by the enter key, so when you type 40 and press Enter it reads '4', then '0' then '\r' and finally '\n' (converting those chars to int). That's why it displays four messages.
Instead you have to read everything typed before the Enter with Console.ReadLine() and then convert this (string) to a double. So in the end you have to do this:
numberguess = double.Parse(Console.ReadLine());
Console.Read() reads a single character as an int. If you're trying to get what the user typed before they hit enter, read the current line, and then parse an integer from it.
int.Parse(Console.ReadLine());

How do I check if the user input is strictly numbers, using the bool type? [duplicate]

This question already has answers here:
Identify if a string is a number
(26 answers)
Closed 5 years ago.
I defined a string data type. Prompted the user to enter 10 numbers. e.g Console.Write("Enter your cell number: ");
I want to know how to validate the string and make sure the user entered numbers only
Best option would be use regular expression to much exactly 10 digits:
Regex pattern = new Regex(#"^\d{10}$");
if(pattern.isMatch(input))
{
//Do something
return true;
}
Another option is to use Int64.TryParse, read more here, but that additional checks are needed, to verify that result had 10 digits (no more, no less), number is not negative etc.
bool result = Int64.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}

How to validate a string so that it's not empty and contains numeric values? [duplicate]

This question already has answers here:
Identify if a string is a number
(26 answers)
Closed 8 years ago.
As I am making a console application I can't seem to get the .Length to check whether it's empty for an if statement to work, says that it's "read only".
I can't simply define the value as int due to using console to retrieve the data.
Console.Write("Enter your Phone Number: ");
phone_number = Console.ReadLine();
You can use int.TryParse(). It returns true if the string is a valid int. If the string is empty or not numeric it will return false. You didn't mention it in your question so I am assuming you aren't entering in decimal numbers (ie. 34.12).
int phoneNumber;
if(int.TryParse(Console.ReadLine(), out phoneNumber))
{
// phone number was an int
}
else
{
// not an int
}
Although not exactly your question, you should use only the digits of your input as a phone number. The format may vary but still be valid:
(+001)555-123456
555 123456
123456
555 12 34 56
All valid answers to the question. Don't make people type their number in ways they never do it. Just accept their input and take what you need:
Console.Write("Enter your Phone Number: ");
var input = Console.ReadLine();
string phoneNumber = new string(input.Where(char.IsDigit).ToArray());
That's very simple.
first you check if the string is null or empty using this Method:
String.IsNullOrEmpty(string value)
if the method returned true it means that you should not continue(the string is null or empty).
then you want to check that if the string can be converted to int(number).so you can use:
public static bool TryParse(
string s,
out int result)
If you want to know more about int.TryParse method,you can refer to http://www.dotnetperls.com/int-tryparse for a simple tutorial.
Happy codding. If you have anymore answers,I'm ready here :D

C# if statement readline must equal number [duplicate]

This question already has answers here:
How can I validate console input as integers?
(10 answers)
Closed 8 years ago.
I can't figure out what to put in brackets to make my program check if the input was number. I would like to return an error if not, and restart the process. Any suggestions?
bool running = true;
Console.Write("Enter the number of victims so we can predict the next murder, Sherlock: ");
while (running)
{
victimCount = int.Parse(Console.ReadLine());
if (/*I want victimCount only to be accepted if it's a number*/)
{
Console.Write("\nThat's an invalid entry. Enter a correct number!: ");
}
else
{
running = false;
}
}
I want victimCount only to be accepted if it's a number
You can use int.TryParse method instead. It returns boolean value that your value is a valid int or not.
string s = Console.ReadLine();
int victimCount;
if(Int32.TryParse(s, out victimCount))
{
// Your value is a valid int.
}
else
{
// Your value is not a valid int.
}
Int32.TryParse method uses NumberStyles.Integer by default. That means your string can have;
Leading CurrentCulture's sign. (PositiveSign or NegativeSign)
Leading white spaces.
Trailing white spaces
as a number stye.
Try this:
int victimcount;
bool is Num = int.TryParse(Console.ReadLine(), out victimcount);
If `isNum` is true then the input is an integer. Use this for your check. At the same time, if the parse succeeds, the parsed value gets assigned to the `victimcount` variable (0 is assigned if it fails).

Evaluate user expression

I am developing a web application where there is a textbox. User enters a condition to show specific color for a "string". This string holds some integer value.
User specifies condition for the string value like this,
>30:"Red"
<20:"Green"
:"Yellow:
This is one condition. It is something like if,elseif,else condition. User can specify only if,else like condition like this
>60:"Blue"
:"White"
(Which means if the string value greater than 60 then get "Blue" as color for the string else "White" is the color for the string)
I have to evaluate color for the string based on the above condition entered in the textbox for each string. There are thousands of strings with values and user will enter such expression for each string.
what is the best way to solve this issue?
String input = getTextBoxInput() // get input from text box
if(input.contains("<") || input.contains("<"))
{
if(input.contains("<"))
{
int index = input.indexOf("<");
String conditionString = input.substring(index+1,input.length());
// condition number is the number being compared
int conditionNumber = conditionString.split(":")[0];
// if condition is true then get the corresponding colour
if(number < conditionNumber){setColor(conditionString.split(":")[1])}
// check if it an if else condition and do the following
else if(input.length()>1){ setColor(conditionString.split(":")[2])}
}
}
This is the basic pseudo code. You can define constants for "<" and ">" . Also you may need to do some exception handling incase of incorrect input.
please see Shunting Yard algorithm , you need to have something similar

Categories