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;
Related
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.
}
I have a snipped of code that I wrote that calculates how long the user has been alive. But the problem is, the program goes to hell if the user doesn't enter a integer e.g January or something else. I need to know how to stop this.
int inputYear, inputMonth, inputDay;
Console.WriteLine("Please enter the year you were born: ");
inputYear = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the Month you were born: ");
inputMonth = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the day you were born: ");
inputDay = int.Parse(Console.ReadLine());
DateTime myBrithdate = new DateTime(inputYear,inputMonth, inputDay);
TimeSpan myAge = DateTime.Now.Subtract(myBrithdate);
Console.WriteLine(myAge.TotalDays);
Console.ReadLine();
if the user doesn't enter a integer e.g January or something else
You can use Int32.TryParse method then..
Converts the string representation of a number in a specified style
and culture-specific format to its 32-bit signed integer equivalent. A
return value indicates whether the conversion succeeded.
Console.WriteLine("Please enter the Month you were born: ");
string s = Console.ReadLine();
int month;
if(Int32.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out month))
{
// Your string input is valid to convert integer.
month = int.Parse(s);
}
else
{
// Your string input is invalid to convert integer.
}
Also TryParse method doesn't throw any exception and that's why you don't need to use any try-catch block with it.
This is far above my level, I have no idea what is going on here.
Ok. I try to explain a little bir more deep.
What you complain is the users input right? Beucase you said, you want to put int as an input. Not string like "January" or "May" etc..
When you read input with Console.ReadLine() method, it returns a string as a return type, not int. Doesn't matter user put as an input 3 or January, this method returns them as a string regardless what they are type is.
3 and January are strings in this case. But how we check these strings are actually convertable to an integer value? This is the part of why we using Int32.TryParse method. This method checks these inputs are convertable to integers or not so we can use this integer in DateTime constructor as a real integer.
This is because you are using int.Parse(Console.ReadLine()); - the int stands for integer. Well you could put a try catch block arround your code.
The original code would stand in the try block, because you want to try to run it- but if an error accours ( e.g. user types jan), the catch block handles the error and your program could go on without troubles.
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);
}
Here's my problem, I'm trying to format a {"C:O"} into a console.readline but I'm getting a method name expected error. here's what I have now:
money = double.Parse(Console.ReadLine()(string.Format("{O:C}")));
In addition to the syntax errors, you should generally use decimal to represent money, since many operations on double can result in round-off errors.
I'd recommend something like this:
string input = Console.ReadLine();
decimal money = decimal.Parse(input);
Or in one line:
decimal money = decimal.Parse(Console.ReadLine());
But Parse will throw an exception if given invalid input (e.g. "foo"). You might want to use TryParse to be a bit safer:
decimal money;
if (!decimal.TryParse(Console.ReadLine(), out money))
{
Console.WriteLine("Invalid input");
}
I'm new to C# programming and I'm not sure what I'm doing wrong because I can't sum up numbers that are Double. If I input 2,5 and 2,5 I get 5, but if I enter 2.5 and 2.5 I get zero when I use a dot instead of a comma between the numbers. Why this?
I add some of my code:
private void ReadInputAndSumNumbers()
{
while (!done)
{
Console.Write("Number: ");
if (double.TryParse(Console.ReadLine(), out num))
{
if (num == 0)
{
done = true;
}
else
{
sum += num;
}
}
}
}
My settings are to use a comma, but I would like the user to be able to enter a value with dot also
How are you converting your ReadLine input into Doubles? Most of the conversion operations are locale-specific, so if your Windows settings have , as the decimal separator, this setting is respected.
Example:
string enteredByUser = Console.ReadLine();
// uses user-specific Windows settings (decimal separator might be ",")
double myDouble1 = double.Parse(enteredByUser);
// uses default settings (decimal separator is always ".")
double myDouble2 = double.Parse(enteredByUser, CultureInfo.InvariantCulture);
A short side note: If you parse user input, you should look into double.TryParse, since this is more robust than double.Parse or Convert.ToDouble, since it allows you to detect faulty input without resorting to exception handling.
EDIT: If you want to support both comma and dot, you need to convert dots into commas (or vice versa) first. String.Replace can help you here. Note, though, that this approach will break if the user tries to enter a thousands separator (1.000,00 -> 1.000.00 or 1,000,00 -> error). The recommended way to do it is to
only accept the decimal separator specified in Windows, if the input comes from an end-user (i.e., keep your code as it is) and
only accept the neutral culture (.), if the input comes from some machine-generated output or file.
A sample for caculate the double sum
static void Main(string[] args)
{
var retVal = 0.0;
var sum = 0.0;
while (true)
{
Console.WriteLine("Enter input:");
string line = Console.ReadLine();
if (line == "exit")
{
break;
}
double.TryParse(line, NumberStyles.Any, CultureInfo.InvariantCulture, out retVal);
sum += retVal;
Console.WriteLine(string.Format("Double Value : {0}", sum ));
}
Console.ReadKey();
}