I'm trying to validate some data and I was wondering is it possible to encode an if statement so that if there is a text value entered instead of a numeric value that it does not crash?
Obviously the standard message indicating that an incorrect message has been entered.
I'll write an example here:
Console.WriteLine("Please enter your height in centimetres please.");
Console.WriteLine("My height is: ");
dHeight = Convert.ToDouble(Console.ReadLine());
if (dHeight == xxxxxx?)
{
Console.WriteLine("Sorry incorrect data entered, please enter a numeric value");
dHeight = Convert.ToDouble(Console.ReadLine());
}
What would I need instead of this as I am not sure how to phrase it/if it is indeed even possible.
You can go with double.TryParse method which will return false if your value cannot be parsed.
double result;
if (double.TryParse(yourstirng, out result))
{
//your string is double do something with the parsed value
result++;
}
else
{
Console.WriteLine("Sorry incorrect data entered, please enter a numeric value");
}
Sure, you can use TryParse, and then if it fails, prompt them again. Note I also added some retry logic here, so that the user cannot proceed until they enter a valid double.
In the code below, I capture their input in a variable (called input) and then use double.TryParse to try to convert it to a double. If the TryParse succeeds, then the double result will contain their converted entry. If it fails, then an error message is displayed and they can try again.
Console.Write("Please enter your height in centimeters: ");
var input = Console.ReadLine();
double result;
while (!double.TryParse(input, out result))
{
Console.Write("{0} is not a valid height. Please try again: ", input);
input = Console.ReadLine();
}
Console.WriteLine("Thank you. You entered a valid height of: {0}", result);
Convert.ToDouble uses double.Parse under the hood, which means that it will throw if an invalid format is encountered (ie. plain text).
Instead, use double.TryParse which does not throw if it fails (it simply returns false):
double dHeight = 0;
if (!double.TryParse(Console.ReadLine(), out dHeight))
{
Console.WriteLine("Some Error Message");
}
else
{
//Parse succeeded! Value is in dHeight.
}
Related
This is the code I have. It works and sends an error to the user when they input something other than a number. What I need to figure out is how to send the same error if they try to enter a string again.
Console.WriteLine("Type in a number and then press enter:");
try
{
num2 = Convert.ToDouble(Console.ReadLine());
}
catch
{
Console.WriteLine("Please Enter a valid numerical value!");
Console.WriteLine("Please enter a valid number and then press enter:");
num2 = double.Parse(Console.ReadLine());
}
double result;
do
{
Console.Write("Type in a number and then press enter: ");
}
while (!double.TryParse(Console.ReadLine(), out result));
Console.WriteLine($"Thanks! {result}");
You should use double.TryParse, which returns a bool indicating whether or not the parsing was successful, and which sets an out parameter to the converted value. Then you can do something like this:
Console.WriteLine("Type in a number and then press enter:");
double userInput;
while (!double.TryParse(Console.ReadLine(), out userInput)
{
Console.WriteLine("Please Enter a valid numerical value!");
Console.WriteLine("Please enter a valid number and then press enter:");
}
// After the above loop, the variable 'userInput' will contain the user's number
This is more intentional than using try/catch to do input validation. For more reading, see: Why are Exceptions said to be so bad for Input Validation?
Create a boolean verifiedNumber then create a while loop
while(!verifiedNumber) {
Console.WriteLine("Type in a number and then press enter:");
try {
num2 = Convert.ToDouble(Console.ReadLine());
verifiedNumber = true;
}
catch {
Console.WriteLine("Please Enter a valid numerical value!");
}
}
As another althernative you can use for loop:
double result;
for(; ; )
{
Console.WriteLine("Type in a number and then press enter:");
if(!double.TryParse(Console.ReadLine(), out result)){
Console.WriteLine("Please Enter a valid numerical value!");
Console.WriteLine("Please enter a valid number and then press enter:");
}
else
{
break;
}
}
Console.WriteLine($"Result = {result}");
so I'm 3 weeks new to programming and I am trying to make a basic Console calculator using C#. I do not know how to read a decimal (eg. 5.5) from a user. Normal integers (e.g. 5) work though. I get the below exception error:
An unhandled exception of type 'System.FormatException' occurred in
mscorlib.dll
Additional information: Input string was not in a correct format.
This is the code:
Console.WriteLine(
"Hi there, My name is Mohammed.\n" +
"Today we are going to be doing several calculations.\n\n" +
"These would include Addition, Subtraction, Multiplication and Division. ");
Console.WriteLine("To get started, please hit the space key.");
Console.ReadKey();
Console.WriteLine("We will start with a addition. Please enter the first number.");
double num01 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Now enter the second number");
double num02 = Convert.ToDouble(Console.ReadLine());
double ans01 = (num01 + num02);
Console.WriteLine(num01 + "+" + num02 + " is equals to " + ans01 +
"\nGreat, now lets move on to subtraction. Please enter the first number.");
I suggest method extraction, something like this:
using System.Globalization;
...
private static double ReadDouble(string title)
{
while (true)
{
Console.WriteLine(title);
string userInput = Console.ReadLine();
double result;
// We use CultureInfo.InvariantCulture to ensure that
// decimal separator is dot (.). i.e. we expect 5.5 input
if (double.TryParse(userInput,
NumberStyles.Any,
CultureInfo.InvariantCulture,
out result))
{
return result;
}
Console.WriteLine("Sorry, incorrect format. Enter it again, please.");
}
}
Then we can use the routine
...
Console.ReadKey();
double num01 = ReadDouble("We will start with a addition. Please enter the first number.");
double num02 = ReadDouble("Now enter the second number");
double ans01 = (num01 + num02);
...
You should check the current culture on your computer. You can go to Control Panel and click Region and Language. From there, click Additional settings button at the bottom. It should take you to the Customize Format page like below
This page tells you how to enter a decimal number on your console. The above steps are for Win 7 machine. You can then try the following C# code to verify the working from the immediate window on Visual Studio
double.Parse("5.5");
double.Parse("5,5");
The correct format will not throw an Exception in the immediate window (or temp code)
Also, the same Decimal symbol can be extracted via C# using the below code
System.Globalization.CultureInfo.CurrentCulture.NumberFormat.PercentDecimalSeparator
So I want to use a TryParse method, but so far I can do it only with integer or double value. However, I want to check if the value is a number, and if it's not (if it is a string for instance) to get a false value. Something like IsDigit() is Java.
static void Main()
{
int number;
Console.Write("Enter a number: ");
bool result = Int32.TryParse(Console.ReadLine(), out number);
if (result)
{
Console.WriteLine("The input number is an integer.");
}
else
{
Console.WriteLine("The input number is not an integer.");
}
}
So I want to do that, but instead of checking for an integer value, I'd like to check for a numerical value. So if anybody can tell me what method I can use I'd be very happy.
Thanks in advance!
use double:
double number;
bool result = double.TryParse(Console.ReadLine(), out number);
This will parse any real number.
TryParse for decimal or double types is your limit for built in methods. If you want more than that, you'd have to parse the string yourself. The can be quite easily done using a regex, such as
^-?[0-9]+\.?[0-9]*([Ee][+-]?[0-9]+)?$
bool result = double.TryParse(mystring, out num);
The double.TryParse also works on integers.
For a single character, there's Char.IsDigit(). In that case you may want to look at Console.ReadKey() instead of reading a whole line. By the way, Char.IsDigit() also matches digits from other cultures.
For multiple characters you'll need to think about what you want to accept. decimals, exponents, negative numbers, or just multiple digit characters?
You could try a regular expression
var regex = new Regex(#"^-*[0-9\.]+$");
var m = regex.Match(text);
if (m.Sucess)
{
Console.WriteLine("The input number is an integer.");
}
else
{
Console.WriteLine("The input number is not an integer.");
}
You can also allow separators by including them in the regex.
static bool enteredNumber()
{
int intValue;
double doubleValue;
Console.Write("Enter a number: ");
string input = Console.ReadLine();
return Int32.TryParse(input, out intValue) ? true : double.TryParse(input, out doubleValue);
}
How do I add a regular expression which will accept decimal places (5.23) but nothing else in a break like so? i.e handle only numbers and decimal places which will throw an error if anything other than this is typed or returned:
case 1:
double[] myArrai1 = new double[3];
Console.WriteLine("Insert a number");
myArrai1[0] = double.TryParse(Console.ReadLine()); // no overload method?
Console.WriteLine("Insert a number");
myArrai1[1] = double.Parse(Console.ReadLine());
Console.WriteLine("Insert a number");
myArrai1[2] = double.Parse(Console.ReadLine());
break;
Cheers guys.
P.s not sure on how to programme it in with the break also has to be without exception.
Regex is a little heavy for validating a double. Use double.TryParse instead (it'll return false if the input is invalid).
double dbl;
if (!double.TryParse(Console.ReadLine(), out dbl))
Console.WriteLine("Invalid input");
You don't need a Regex for this.
You can simply use decimal.Parse or double.Parse - if the input string is in the wrong format, you will get a FormatException.
The code you posted appears to be right - what's not working?
try this :
/^\d+(\.\d{1,2})?$/;
Regex regex = new Regex ("^\d+(\.\d{1,2})?$");
MatchCollection matches = regex.Matches(text);
if (matches.Count>0)......
You will probably be better off just using .NET's double parsing instead of trying to re-invent it in Regex. You can use Double.TryParse to test the string and do the conversion if the number can be parsed:
Console.WriteLine("Insert a number");
string input = Console.ReadLine();
double value;
if (!Double.TryParse(input, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
throw new InvalidOperationException(String.Format("{0} could not be parsed as a valid number.", input));
Did you want to just validate what the user inputs, or stop them from putting in invalid characters in the first place?
In the first case, regex aren't really needed. You are on the right track with double.Parse, but what you want to do is double.TryParse. First read the user input into a string, then TryParse it into a double. If TryParse returns false, tell you user their input is invalid and prompt them to enter it again.
FWIW: here's how I'd do it (warning: untested code), which may or may not be what you need:
case 1:
double[] myArrai1 = new double[3];
for (int i=0; i < myArrai1.length; i++) {
Console.WriteLine("Insert a number");
while (!double.TryParse(Console.Readline(), out myArrai1[i])) {
Console.WriteLine("Invalid entry. Please enter a number.");
}
}
break;
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.