I have another question about the TryParse method I have created to check for my user's input. Sorry for my extra question, but I ran into another complication and wanted more assistance on it, so I made another question since my last one is quite old. I was afraid no one would see this question if I post it on the last one.
There are no errors, but when I try to run it to test what my user's input, for everything I enter, including whole numbers, decimals, (1.00, 1.0, 1,000.0) it gives me the Messagebox.Show anyway. Here's what I created:
{
// Arrange the variables to the correct TextBox.
decimal Medical;
if (!decimal.TryParse(ChargeLabel.Text, out Medical))
{
MessageBox.Show("Please enter a decimal number.");
}
decimal Surgical;
if (!decimal.TryParse(ChargeLabel.Text, out Surgical))
{
MessageBox.Show("Please enter a decimal number.");
}
decimal Lab;
if (!decimal.TryParse(ChargeLabel.Text, out Lab))
{
MessageBox.Show("Please enter a decimal number.");
}
decimal Rehab;
if (!decimal.TryParse(ChargeLabel.Text, out Rehab))
{
MessageBox.Show("Please enter a decimal number.");
}
// Find the cost of Miscs by adding the Misc Costs together.
decimal MiscCharges = Medical + Surgical + Lab + Rehab;
ChargeLabel.Text = MiscCharges.ToString("c");
In other words, I try to input any form of numbers on the Medical, Surgical, Lab, and Rehab textboxes and it still gives me the same MessageBox. Will someone provide me help on how to let my application check my user's input correctly? Thanks you, and sorry again.
Make sure that you are entering numbers in a culture-correct format. Some cultures use comas as separators, others use dots. Try "123,4" and "123.4"
You are using the same label in each parsing statement.
decimal.TryParse(ChargeLabel.Text, out Medical)
decimal.TryParse(ChargeLabel.Text, out Surgical)
decimal.TryParse(ChargeLabel.Text, out Lab)
decimal.TryParse(ChargeLabel.Text, out Rehab)
EDIT I'd recommend putting a breakpoint in each MessageBox.Show line, then seeing what the string value you're parsing is.
You can also provide more information in the message shown:
decimal Rehab;
if (!decimal.TryParse(ChargeLabel.Text, out Rehab))
{
MessageBox.Show(string.Format("Unable to parse '{0}' as a decimal number.", ChargeLabel.Text));
}
Related
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());
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
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.
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 have a Windows forms application written in C#.
I am looking for a way to validate my price textBox so that it only accepts prices in a double format e.g. allowing 0.01 & 1200.00 but provides an error when the user enters characters.
I would except the code to looks similar to
String price = tbx_price.Text.Trim();
if price is not a number
{
error message
}
else{
...
What method could I use to check if the price string contains only numbers? Please note that I require the user to be able to use decimal places so the '.' character should be allowed.
Use decimal.TryParse :
decimal d;
if (!decimal.TryParse(price, out d)){
//Error
}
And if you also want to validate the price (145.255 is invalid):
if (!(decimal.TryParse(price, out d)
&& d >= 0
&& d * 100 == Math.Floor(d*100)){
//Error
}
You can test this using decimal.TryParse().
For example:
decimal priceDecimal;
bool validPrice = decimal.TryParse(price, out priceDecimal);
If you can't be sure that the thread culture is the same as the user's culture, instead use the TryParse() overload which accepts the culture format (also the number format which you can set to currency):
public bool ValidateCurrency(string price, string cultureCode)
{
decimal test;
return decimal.TryParse
(price, NumberStyles.Currency, new CultureInfo(cultureCode), out test);
}
if (!ValidateCurrency(price, "en-GB"))
{
//error
}
Besides using the answer marked as accepted in order to avoid the problem with culture about prices, you can always use this
Convert.ToDouble(txtPrice.Text.Replace(".", ","));
Convert.ToDouble(txtPrice.Text.Replace(",", "."));
this will depend how you manage your convertion in your app.
PS: I could not comment the answer because i do not have the neccesary reputation yet.