How Do I only accept Numeric Digits in C# Xamarin - c#

I'm New to C# with Xamarin. Im using Visual Studio for Mac Preview to work on an iOS app.
When Making a basic calculator I can't figure out how to not accept answers that aren't a numeric digit. For example in my Text box if I put in a letter I want an error that says
"Please enter a numeric digit".
I don't know why I'm getting an error but its not working.
When I run it and put in a number it just defaults to the else statement every time. Also with Letters. And when I put too many letters in it crashes.
partial void AddButton_TouchUpInside(UIButton sender)
{
double number1 = 0.00;
double answer = 0.00;
double number2 = 0.00;
int value;
string input = Console.ReadLine();
if (Int32.TryParse(input, out value))
{
number1 = double.Parse(Number1TextBox.Text);
number2 = double.Parse(Number2TextBox.Text);
answer = number1 + number2;
AnswerLabel.Text = "The answer is: " + answer.ToString();
}
else
{
InvalidLabel.Text = "Please enter a Numeric Digit";
}
}

I think the problem is string input = Console.ReadLine();
Why are you expecting a correct value with that statement? That would be valid for a console program but you are running an iOS app.
It would make sense something like:
string input = YourTextInput.Text;
If you want to restrict the text input to a keyboard with numbers, use the following:
YourTextInput.KeyboardType = UIKeyboardType.NumberPad;
And one more thing. If the answer should be a double, you should use double.TryParse(input, out value) instead of int.
What about this?
double number1 = 0.00;
double answer = 0.00;
double number2 = 0.00;
if (double.TryParse(Number1TextBox.Text, out number1)
&& double.TryParse(Number2TextBox.Text, out number2))
{
answer = number1 + number2;
AnswerLabel.Text = "The answer is: " + answer.ToString();
}
else
{
InvalidLabel.Text = "Please enter a Numeric Digit";
}
You still need to validate the number entered, as the number pad allows to type more than one decimal point.

I'd recommend changing the TextBox so the keyboard which appears is numeric only.
<Entry Keyboard="Numeric" />
Check out this Xamarin Guide for more info.

Related

Comparing data types in "if" statements in C#?

So, I'm creating a simple calculator getting started into programming in C# and I've had two issues so far that I have not been able to solve.
The first being that for some reason, of all operators/symbols, it won't let me add the "-" operator/symbol alongside a string. It only allows me to have the "-" operator with my variables alone. (I tried using double instead of decimal but got the same error).
The second (and more important) being that I'm trying to have an if statement that gives a message (and run another method) when the user inputs the wrong data type. Any way to solve this (or at least find a work-a-round)?
Thanks!
Here's a sample of the code containing both issues:
static void Calc()
{
Console.Write("\n\nPlease enter a number here: ");
decimal num1 = Convert.ToDecimal(Console.ReadLine());
Console.Write("Please Specify an operator: ");
string op = Console.ReadLine();
Console.Write("Please enter another number: ");
decimal num2 = Convert.ToDecimal(Console.ReadLine());
if (op == "+")
{
Console.WriteLine("The answer is: " + num1 + num2);
}
else if (op == "-")
{
Console.WriteLine("The answer is: " + num1 - num2);
}
else if (op == "*")
{
Console.WriteLine("The answer is: " + num1 * num2);
}
else if (op == "/")
{
Console.WriteLine("The answer is: " + num1 / num2);
}
else
{
OpElse();
}
if (num1 || num2 != Decimal)
{
Console.WriteLine("You must input a number");
Else();
}
I'm trying to have an if statement that gives a message (and run another method) when the user inputs the wrong data type. Any way to solve this (or at least find a work-a-round)?
You can try the Decimal.TryParse method, which will attempt to parse a string to a decimal, but wont throw an exception if it fails. It would look something like this:
if (!Decimal.TryParse(Console.ReadLine(), out decimal num1))
{
Console.WriteLine("No no my friend. You have to enter a valid number.");
}
..of all operators/symbols, it won't let me add the "-" operator/symbol alongside a string. It only allows me to have the "-" operator with my variables alone. (I tried using double instead of decimal but got the same error).
That has to do with operator precedence. In fact, even though minus is the only one that complains at compile time, the addition gives you are wrong result at runtime. The problem is just that the (first) + is being evaluated before the -. That results in the first number being added to the string, before doing the calculation. To fix this, simply wrap the calculation part in parenthesis:
Console.WriteLine("The answer is: " + (num1 - num2));
or move the calculation out of the string concatenation:
var result = num1 + num2;
Console.WriteLine("The answer is: " + result);
In the line:
Console.WriteLine("The answer is: " + num1 - num2);
It will add firstly num1 to the string, and then will try to subtract number from string, which is invalid. Use parenthesis "some string" + (num1 - num2)
Same error will happen with addition as well, for example: "a" + 5 + 2 will result in: a52
To check if entered data is incorrect, TryParse can be used, or same Convert.ToDecimal but with try catch
Console.Write("\n\nPlease enter a number here: ");
decimal num2 = 0; // Assigning default value so compiler doesn't comlain
try
{
num2 = Convert.ToDecimal(Console.ReadLine());
}
catch (FormatException e)
{
//do something else
}
num1 and num2 are always going to be decimal type so checking if their type is a decimal is unnecessary. If you want to display a message when parsing fails, look into using decimal#TryParse() which will return true if it parsed correctly, false if not.
As for your - sign issue. I'm not too sure what you mean but I'm assuming you're trying to do something like -"some string" which is invalid C# code. Decimal could convert negative numbers just fine when typed out, assuming you don't put a space between the minus and the number itself.
Or if you're trying to do something like "num1 - num2" that won't work unless you use string interpolation $"{num1+num2}" for an example
You correctly pointed out two problems:
1. Operator Failure
The + - * / operators. Remember order of operations, * / are first, + - are second, then left to right in groups of equal order. So in the write statements the * / get executed before the +. Resulting string + decimal, and since there is implicit converter from decimal to string the + operator acts as a concatenation.
In the case of - the order is string + decimal - decimal, which from left to right means the first + concatenates two strings. However, - is not an operator on string and therefore fails.
Try using the $"Answer is: {num1 + num2}" syntax for each case (changing the operator as required).
2. Logic Failure
You are converting and throwing a runtime exception in the Parse method prior to the tests and out put. As suggested, use TryParse and place the error case at the top.

Errors in library fee code using multiple methods

I'm making a library program that asks for users to input the amount of books checked out and the amount of days they are over due. If its under or equal to 7 days they are charge 10 cents for each book over due after 7 days its 20 cents for each book. We are supposed to use more than one method and I get two errors:
Use of unassigned local variable 'totalCharge'
There is no argument given that corresponds to the required formal parameter 'daysOverdue' of Program.charge(double,double,double)'
I think I know what the first error means but I thought I already declared it a variable in the first line.
Here's the code so far:
static void Main(string[] args){
double totalCharge;
Console.WriteLine("Please enter the number of books checked out.");
double booksChecked = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the number of days they are
overdue.");
double daysOverdue = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your total charge for {0} days overdue is {1}.",
daysOverdue, totalCharge.ToString("C"));
Console.ReadKey();
totalCharge = charge();
}
private static double charge (double daysOverdue, double booksChecked,
double totalCharge)
{
if (daysOverdue <= 7)
{
return totalCharge = booksChecked * daysOverdue * .10;
}
else
{
return (booksChecked * .70) + (booksChecked) * (daysOverdue - 7)
* (.20);
}
}
}
}
Your code has a number of problems, which I'll review here. My corrections are at the end of this answer. I recommend putting your code and mine side by side and reviewing the differences carefully.
First, you cannot read the value out of a variable before you have assigned a value. You must assign something to it first.
You need to call charge(...) before printing out the value of totalCharge.
Second, you don't need to pass the value of totalCharge to your charge(...) method: it returns the total charge! So remove that parameter entirely.
Third, you need to pass parameters to the charge method.
Fourth, you had some formatting problems. Please review my code to see how I've formatted my code differently. If a line of code is continued onto the next line, use indentation to reflect this. According to C# conventions, function names should be capitalized.
Lastly, this isn't necessarily a problem, but it doesn't look 'right': in two places, you are assigning Convert.ToInt32(...) to a double. Why? Those should be integers.
static void Main(string[] args)
{
Console.WriteLine("Please enter the number of books checked out.");
double booksChecked = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the number of days they are overdue.");
double daysOverdue = Convert.ToInt32(Console.ReadLine());
// assign before printing out value
// pass the two parameters into the function
double totalCharge = Charge(daysOverdue, booksChecked);
Console.WriteLine("Your total charge for {0} days overdue is {1:C}.",
daysOverdue,
totalCharge);
Console.ReadKey();
}
private static double Charge(double daysOverdue, double booksChecked)
{
if (daysOverdue <= 7)
{
return booksChecked * daysOverdue * .10;
}
else
{
return (booksChecked * .70) + booksChecked * (daysOverdue - 7) * (.20);
}
}

Error in calculation Winforms C#

I am building C# WinForms application which has 3 textboxes. First two take value and after calculation show value in third textbox. It has to be in textbox so user can change value if thinks that calculation is wrong. Everything works perfect, but when I run app on windows 7 I get huge error, it calculates that (for example ) 2 times 2.15 is 430. Why is that happening ? I tried installing latest .Net framework on that computer but still doesn't work and after research I have no further ideas.
num1 = num2 = sum = 0;
if (tbNum1.Text.Contains(","))
{
tbNum1.Text = tbNum1.Text.Replace(",", ".");
}
double.TryParse(tbNum1.Text, out num1);
if (tbNum2.Text.Contains(","))
{
tbNum2.Text = tbNum2.Text.Replace(",", ".");
}
double.TryParse(tbNum2.Text, out num2);
sum = num1 * num2;
sum = Math.Round(sum, 2);
tbSum.Text = sum.ToString();
Also, additional two problems appear with displaying WinForm.
First is that panels have different sizes and positions than I programatically set.
Secont is that ( and I suppose that is my fault because I am probably doing that wrong ) all panels show very slow. What I have is like 6 panels with particular dimensions and 6 buttons. Depending on pressed button, I set all panels visible to false and only correct panel visible to true. But it loads very slow. Do you have any suggestions ? Thanks a lot in advance !
Your parse to a double is wrong. You can do it like this:
double num1, num2, product = 0;
if (tb1.Text.IndexOf(",") != -1)
{
tb1.Text = tb1.Text.Replace(",", ".");
}
num1 = double.Parse(tb1.Text, System.Globalization.CultureInfo.InvariantCulture);
if(tb2.Text.IndexOf(",") != -1)
{
tb2.Text = tb2.Text.Replace(",", ".");
}
num2 = double.Parse(tb2.Text, System.Globalization.CultureInfo.InvariantCulture);
product = Math.Round(num1 * num2,2);
tb3.Text = product.ToString();
The character that double.Parse recognizes as the decimal separator depends on the supplied IFormatProvider; if you don't supply any, that's the one for the current culture.
If you specifically want to use the dot as the decimal separator, you can just use CultureInfo.InvariantCulture:
double.TryParse(tbNum2.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out double num);

How to check for a double type response in an if statement

I'm trying to check if the user's response is a double or an int, but the int is specific, whereas the double is not, as I probably made a right mess of explaining it, here's the code:
Console.WriteLine("\n 2) Q: How old is Sally? \n");
int nSallyAge = Convert.ToInt32(Console.ReadLine());
double dSallyAge = Convert.ToDouble((nSallyAge));
if (nSallyAge == 62 || dSallyAge == 62.0)
{
// Increase Score
sUser1Score++;
Console.WriteLine("\n A: Correct, Sally's age is 62, you have been awarded 1 point. \n");
Console.ReadLine();
}
What I'm trying to do, is instead of dSallyAge HAS to equal 62.0, it just has to equal any double figure.
I would approach this problem by first creating a method that gets a double from the user (that will, of course, also accept an int). This removes error handling from your main code.
NOTE in the code below, Math.Truncate can be replaced by Math.Floor, with the same result:
private static double GetDoubleFromUser(string prompt)
{
double input;
while (true)
{
if (prompt != null) Console.Write(prompt);
if (double.TryParse(Console.ReadLine(), out input)) break;
Console.WriteLine("Sorry, that is not a valid number. Please try again.");
}
return input;
}
Then, in my main code, I would get the number from the user, and use the Math.Truncate method to just read the first part of the double passed in by the user (this is what it sounds like you want to do). This means that if the user enters anything from 62 to 62.0 to 62.999, it will truncate the result to '62':
double nSallyAge = GetDoubleFromUser("2) Q: How old is Sally? ");
if (Math.Truncate(nSallyAge) == 62)
{
// Increase Score
sUser1Score++;
Console.WriteLine("A: Correct, Sally's age is 62, you have been awarded 1 point.");
Console.ReadLine();
}
Other alternative ways to use this are:
int sallyAge = Math.Truncate(GetDoubleFromUser("2) Q: How old is Sally? "));
if (sallyAge == 62)
{
// Increase Score
sUser1Score++;
Console.WriteLine("A: Correct, Sally's age is 62, you have been awarded 1 point.");
Console.ReadLine();
}
Or, you could use an input function that returns an int in the first place:
private static int GetIntFromUser(string prompt)
{
return Math.Truncate(GetDoubleFromUser(prompt));
}
In your code above, you are converting the input to an integer and then converting the int result to a double.
Assuming that you are only allowing numerical values to be entered, why not try something like this. This will identify if the input contained decimals or not:
string input = Console.ReadLine();
int iSallyAge;
double dSallyAge;
if (!Int32.TryParse(input, iSallyAge))
{
dSallyAge = Double.Parse(input);
}
You should be using Double.TryParse to parse the user input to a double and then test that value to see whether it's equal to 62.0.
double age;
if (double.TryParse(Console.ReadLine(), out age) && age == 62.0)
{
// age is 62.
// ...
}

How can I read user input from the console?

I want to get a number from the user, and then multiply that number with Pi. my attempt at this is below. But a contains gibberish. For example, if I insert 22, then a contains 50. What am I doing wrong? I don't get any compiler errors.
double a,b;
a = Console.Read();
b = a * Math.PI;
Console.WriteLine(b);
I'm not sure what your problem is (since you haven't told us), but I'm guessing at
a = Console.Read();
This will only read one character from your Console.
You can change your program to this. To make it more robust, accept more than 1 char input, and validate that the input is actually a number:
double a, b;
Console.WriteLine("istenen sayıyı sonuna .00 koyarak yaz");
if (double.TryParse(Console.ReadLine(), out a)) {
b = a * Math.PI;
Console.WriteLine("Sonuç " + b);
} else {
//user gave an illegal input. Handle it here.
}
a = double.Parse(Console.ReadLine());
Beware that if the user enters something that cannot be parsed to a double, an exception will be thrown.
Edit:
To expand on my answer, the reason it's not working for you is that you are getting an input from the user in string format, and trying to put it directly into a double. You can't do that. You have to extract the double value from the string first.
If you'd like to perform some sort of error checking, simply do this:
if ( double.TryParse(Console.ReadLine(), out a) ) {
Console.Writeline("Sonuç "+ a * Math.PI;);
}
else {
Console.WriteLine("Invalid number entered. Please enter number in format: #.#");
}
Thanks to Öyvind and abatischev for helping me refine my answer.
string input = Console.ReadLine();
double d;
if (!Double.TryParse(input, out d))
Console.WriteLine("Wrong input");
double r = d * Math.Pi;
Console.WriteLine(r);
The main reason of different input/output you're facing is that Console.Read() returns char code, not a number you typed! Learn how to use MSDN.
I think there are some compiler errors.
Writeline should be WriteLine (capital 'L')
missing semicolon at the end of a line
double a, b;
Console.WriteLine("istenen sayıyı sonuna .00 koyarak yaz");
a = double.Parse(Console.ReadLine());
b = a * Math.PI; // Missing colon!
Console.WriteLine("Sonuç " + b);
string str = Console.ReadLine(); //Reads a character from console
double a = double.Parse(str); //Converts str into the type double
double b = a * Math.PI; // Multiplies by PI
Console.WriteLine("{0}", b); // Writes the number to console
Console.Read() reads a string from console A SINGLE CHARACTER AT A TIME (but waits for an enter before going on. You normally use it in a while cycle). So if you write 25 + Enter, it will return the unicode value of 2 that is 50. If you redo a second Console.Read() it will return immediately with 53 (the unicode value of 5). A third and a fourth Console.Read() will return the end of line/carriage characters. A fifth will wait for new input.
Console.ReadLine() reads a string (so then you need to change the string to a double)
Sometime in the future .NET4.6
//for Double
double inputValues = double.Parse(Console.ReadLine());
//for Int
int inputValues = int.Parse(Console.ReadLine());
double a,b;
Console.WriteLine("istenen sayıyı sonuna .00 koyarak yaz");
try
{
a = Convert.ToDouble(Console.ReadLine());
b = a * Math.PI;
Console.WriteLine("Sonuç " + b);
}
catch (Exception)
{
Console.WriteLine("dönüştürme hatası");
throw;
}
Console.Read() takes a character and returns the ascii value of that character.So if you want to take the symbol that was entered by the user instead of its ascii value (ex:if input is 5 then symbol = 5, ascii value is 53), you have to parse it using int.parse() but it raises a compilation error because the return value of Console.Read() is already int type. So you can get the work done by using Console.ReadLine() instead of Console.Read() as follows.
int userInput = int.parse(Console.ReadLine());
here, the output of the Console.ReadLine() would be a string containing a number such as "53".By passing it to the int.Parse() we can convert it to int type.
You're missing a semicolon: double b = a * Math.PI;

Categories