C# if statement readline must equal number [duplicate] - c#

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

Related

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

Checking if user input is a letter [duplicate]

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`
}

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

check the string having full number or the combinbation of number and string [duplicate]

This question already has answers here:
Regex for numbers only
(20 answers)
Closed 9 years ago.
I want to check whether a string is only numeric, or is alphanumeric.
For example :
string test = "2323212343243423333";
string test1 = "34323df23233232323e";
I want to check test having number only or not. If the whole string having number means it returns true. Otherwise it returns false.
How can i do this?
bool allDigits = text.All(c => char.IsDigit(c));
Or
bool allDigits = text.All(char.IsDigit);
Unless by "numeric" you include hex numbers? My answer only works for strings that contain only digits, of course.
if the string length is not too long, you may try int.TryParse(string here) or you may write the function yourself by checking every character in the string like
if(MyString[i]-'0'<= 9 && MyString[i]-'0'>= 0)
//then it's a digit, and check other characters this way

Char tryParse not working as I thought?

I have some problem with a method that I have done in c#. I'm trying to stop user from entering anything else then y and n. It's almost working that I want, but user can still enter more than one sign, and then it doesn't work! How can I do to also check if char is more than one char? I thought the tryParse solved that? Thanks!
// Method to check if item is food or not
private void ReadIfFoodItem()
{
Console.Write("Enter if food item or not (y/n): ");
if (char.TryParse(Console.ReadLine(), out responseFoodItem))
{
if(Char.IsNumber(responseFoodItem))
{
Console.WriteLine(errorMessage);
ReadIfFoodItem();
}
else
{
// Set true or false to variable depending on the response
if ((responseFoodItem == 'y' || responseFoodItem == 'Y'))
{
foodItem = true;
selectedVATRate = 12; // Extra variable to store type of VAT
}
else if ((responseFoodItem == 'n' || responseFoodItem == 'N'))
{
foodItem = false;
selectedVATRate = 25; // Extra variable to store type of VAT
}
else
{
Console.WriteLine(errorMessage);
ReadIfFoodItem();
}
}
}
}
The following code "works" in that it produces the expected results.
char responseFoodItem;
Console.Write("Enter if food item or not (y/n): ");
if (char.TryParse(Console.ReadLine(), out responseFoodItem))
{
// Set true or false to variable depending on the response
if ((responseFoodItem == 'y' || responseFoodItem == 'Y'))
{
Console.WriteLine("foodItem = true");
}
else if ((responseFoodItem == 'n' || responseFoodItem == 'N'))
{
Console.WriteLine("foodItem = false");
}
else
{
Console.WriteLine("Unrecognised input");
}
}
else
{
Console.WriteLine("Invalid input");
}
However, has others have pointed out using ReadKey is a better solution if you want to limit the input to a single key. It also means that the user doesn't have to press the Return/Enter key for the input to be accepted.
char represents a single character, so How can I do to also check if char is more than one char? I thought the tryParse solved that? seems a bit nonsensical... TryParse will try and parse a single character from your input and will explicitly fail if the value is null or has a length > 1.
Instead of checking a character, just check the string, e.g.:
string line = Console.ReadLine();
switch (line.ToUpperInvariant())
{
case "Y":
// Do work for y/Y
break;
case "N":
// Do work for n/N
break;
default:
// Show error.
break;
}
char.TryParse simply tries to parse the string supplied as an argument, it does not limit the number of characters that you can input to the console using Console.ReadLine.
When the user inputs more than a single character, char.TryParse will fail because the string returned by Console.ReadLine doesn't contain a single character.
You should use Console.Read instead.
How can I do to also check if char is more than one char?
string line = Console.ReadLIne();
If(!string.IsNullOrEmpty(line) && line.Length > 1)
for reading a single char use Console.ReadChar() instead.
Console.ReadLine allows users to type a string of any length and press enter.
How can I do to also check if char is more than one char? I thought the tryParse solved that?
From the manual page:
Converts the value of the specified string to its equivalent Unicode character. A return code indicates whether the conversion succeeded or failed....The conversion fails if the s parameter is null or the length of s is not 1.
Have you tried using Console.ReadKey instead of ReadLine?
To check it the user has inserted more then one char you could check the string length instead of use Char.TryParse
......
private void ReadIfFoodItem()
{
string answer=string.empty;
Console.Write("Enter if food item or not (y/n): ");
answer=Console.ReadLine()
if (answer.lenght>=1))
{
//error
.......
}
...............
This answer should help you: How can I limit the number of characters for a console input? C#
The console does not limit the user input (well it does, but to 256 characters), nor does char.TryParse which doesn't do anything at all to limit the input length.
You can try using Console.ReadKey
It's just one keystroke for the user and you know there won't be more than one char.
Why not comparing to the input'ed string?
And why not simplifying the comparison?
using System.Linq;
private static string[] ValidAnswers = new string[]{ "y", "yes" };
// Method to check if item is food or not
private void ReadIfFoodItem() {
Console.Write("Enter if food item or not (y/n): ");
string ans = Console.ReadLine();
// Checks if the answer matches any of the valid ones, ignoring case.
if (PositiveAnswers.Any(a => string.Compare(a, ans, true) == 0)) {
foodItem = true;
selectedVATRate = 12; // Extra variable to store type of VAT
} else {
foodItem = false;
selectedVATRate = 25; // Extra variable to store type of VAT
}
}
Alternatively, as others said, you can use Console.ReadKey().
Use Console.ReadKey() to limit the amount of characters. To test whether you have a Y or an N then you can compare the ASCII codes or use a regular expression.

Categories