How many days user has been alive calculator - c#

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. 

Related

C# Wrong Value stored in variable

I am fairly new to programming so have some mercy ;)
I am trying to build a program that can solve equations and give gradient and so on in c#, so I can make it more complex gradually. Problem is, there appears to be a wrong value from my input when I tried to start building it.
Console: Given value for "a":
9 The Output: 57
My Code:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Input an linear Eqasion in the following Pattern -- a * x + b");
Console.Write("Given value for \"a\":");
decimal aValue;
aValue = Console.Read();
Console.Write(aValue);
}
}
}
Console.Read() returns an int, but not in the way you think. It returns the numeric value of the typed character, not the human-intuitive interpretation of a character that coincidentally happens to be a number. Consider for example what it would return if you type a letter, or any other non-numeric character.
And what is the numeric (decimal) value for the character '9'? 57 is.
It sounds like you want to read the line, not the character. For example:
string aValue;
aValue = Console.ReadLine();
Console.Write(aValue);
Remember that you'll need to press return to send the line to the application.
If you'll later need the value to be numeric, you'll still want to input the string but will want to parse it. For example:
string aValue;
aValue = Console.ReadLine();
if (decimal.TryParse(aValue, out decimal numericValue)
{
Console.Write(numericValue);
}
else
{
// The value could not be parsed as a decimal, handle this case as needed
}
Console.Read returns the character code entered on the command line in this scenario. The ASCII character code of 9 is 57. If you're wanting numeric input, you'd be better using Console.ReadLine with Decimal.Parse (or better yet, Decimal.TryParse)
It is also worth noting that Console.Read only returns one character at a time, meaning for any inputs past 1 digit you'll need special handling. I highly recommend using ReadLine and parsing the string over handling converting the character codes to the number they represent.

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

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

Format user inputed currency

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

Regex C# console app

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;

Categories