Check answer button has incorrect input string format - c#

I am trying to create a check answer button. I have not learned how to use methods yet so i cannot use them in this. I first need to check if the math operation is subtraction or addition and then go from there. Visual studio does not detect any errors but when i run the program and try to check the answer ive inputted i get an error telling me unhandled exception has occured and that input string was not in correct format. I have a feeling the proble is with my int lblMath but im not sure how else to check what the value is inside of that lbl.
{
int First = int.Parse(lblFirst.Text);//The first number in the math equation
int Second = int.Parse(lblSecond.Text);//The second number in the math equation
int UserAnswer = Convert.ToInt32(txtAnswer.Text);//The users answer to math question
int lblMath = int.Parse(lblMathType.Text);//Whether the symbol is + or -
if(lblMath == '+')
{
int AnswerAdd = First + Second;
//Answer is addition
if(UserAnswer == AnswerAdd)
{
MessageBox.Show("Correct");
}
else if(UserAnswer != AnswerAdd)
{
MessageBox.Show("Wrong Answer");
}
}
else if (lblMath == '-')
{
int AnswerSub = First - Second;
//Answer is subtraction
if(UserAnswer == AnswerSub)
{
MessageBox.Show("Correct");
}
else if (UserAnswer != AnswerSub)
{
MessageBox.Show("Wrong Answer");
}
}

You're expecting this to be an integer:
int lblMath = int.Parse(lblMathType.Text);
But then you're immediately expecting it to be a string:
if(lblMath == '+')
(I'm honestly surprised this even compiles.)
What integer value to you expect the string "+" to be and why? The exception is telling you that the string "+" is not an integer. Because it isn't.
It's a string. Use it as a string:
string lblMath = lblMathType.Text;

Related

how to make user input int null value c#

I'm trying to make a program that takes a number and print it on screen but if the user press enter the code ask the user to enter the number again but instead it shows me a exception
Enter_No:
Console.WriteLine("enter number");
int? n = Convert.ToInt32(Console.ReadLine());
if (n == (int?)null)
{
goto Enter_No;
}
else
{
Console.WriteLine(n);
}
Use int.TryParse:
int? num = null;
while(!num.HasValue)
{
Console.WriteLine("Please enter an integer:");
num = int.TryParse(Console.ReadLine(), out int i) ? i : new int?();
}
Console.WriteLine("Entered integer: " + num.Value);
Tim's solution is wonderfully compact. Here's why your attempt failed.
From MSDN, Convert.ToInt32() throws a FormatException if:
value does not consist of an optional sign followed by a sequence of digits (0 through 9).
The preferred approach is int.TryParse(), as it returns false if it's unable to parse the integer rather than throwing an exception.
While the goto keyword is supported in C#, there are few or no situations (depending on who you ask) where it's the best option for flow control. Tim's while loop is an excellent approach.
First, don't use Go To:
Second: Inspect your data and use tryparse:
bool success = false;
do
{
Console.WriteLine("enter number");
var n = Console.ReadLine();
if (n == null)
{
// goto Enter_No;
}
else
{
int typedNum;
success = int.TryParse(n, out typedNum);
Console.WriteLine(typedNum);
}
} while (!success);

How do i check if an input matches a specific letter?

I can't figure out how to check whether the input is a specific letter. I know how to check if it's a specific int/double but when it's a string I don't know what to do.
Any help would be greatly appreciated. I'm just trying to make a basic 3 question quiz that checks whether the user answers with the correct letter (a, b or c) and then adds that to the current score.
class Program
{
static void Main()
{
var a1 = "a";
var a2 = "b";
var a3 = "c";
var qa = 0;
while (qa != 3)
{
if (qa == 0)
{
Console.Write("What is the answer to question 1? ");
var entry1 = Console.Read();
if()
{
}
}
else if (qa == 1)
{
Console.Write("What is the answer to question 2? ");
Console.ReadLine();
}
else if (qa == 2)
{
Console.Write("What is the answer to question 3? ");
Console.ReadLine();
}
}
}
}
For example operator == can't be applied to strings
this is not true. It can be applied:
if(entry.ToString() == a1)
The documentation for the == operator tells us:
For the string type, == compares the values of the strings
another possibility would be to use the String.Equals method
if(entry.ToString().Equals(a1))
EDIT:
Looking closer at your code I realized that you are using Console.Read
which
Reads the next character from the standard input stream.
That means that it returns a char (and only 1).
I guess you want the entire line that the user types in. So you should use ReadLine instead. It returns a string and allows you for a direct comparison
string entry1 = Console.ReadLine();
if(entry == a1)
when you use var for the declaration of types the compiler infers the type and the error becomes obvious at a later stage. you cannot use the == operator on string and char . Read() returns a char so that's why you were not able to compare it in the first place
Note that in "Question 1" you wrote Console.Read(), (not Console.ReadLine()) which returns a char, not a string. So "==" cannot be applied to entry1 and a1 since entry1 will be a char while a1 is a string.
If you compare compatible variables, everything should be fine
string input1;
var input2 = "";
var input3 = 0;
// assign some input values, then compare
// strings
if (input1 == "a") // ok
{ }
if (input2 == "a") // ok
{ }
if (input3 == "a") // not ok, comparing int to string
{ }
// numbers
if (input1 == 1) // not ok, comparing string to int
{ }
if (input3 == 1) // ok
{ }
If you want to, you could try matching the ASCII value of the character by using Console.Read();. This would eliminate the need to press enter. If you were trying to match to uppercase A:
int input = Console.Read();
if (input == (int)char.GetNumericValue(A))
{
Console.WriteLine("True");
Console.Read();
}
else
{
Console.WriteLine("False");
Console.Read();
}

C# If(textbox.text=number) error

I making a quiz in which users would have to enter a number (e.g. 4) into a TextBox then the program would check if the number entered is correct. Unfortunately, I'm having some trouble with this part of the code.
So currently I have this code:
if(textbox1.Text=4)
but the 4 is underlined with the error message:
cannot implicitly convert type 'int' to 'string'.
Can I trouble you all to help me find out what's wrong with my code? Thank you so much!!
Since textbox1.Text is of type string, you have to parse:
int answer;
// TryParse - the value entered can be treated as a valid integer
// answer == correctAnswer - the answer provided is a correct one
if (int.TryParse(textbox1.Text, out answer) && answer == correctAnswer) {
...
}
Please, notice that the implementation tolerates leading and traling spaces (typical problem in quizes): if user happens to input "4 " (trailing space) the answer will be accepted providing that correctAnswer == 4
if(textbox1.Text == Convert.ToString(4))
or
if(textbox1.Text == "4")
You need to parse to int
if(Int32.Parse(textbox1.Text) == 4)
You are comparing a string (textbox1.Text) with an integer (4). To make this work you have to compare same data types. Some options:
if(textbox1.Text == "4")
or
if(textbox1.Text == 4.ToString())
or
if(int.Parse(textbox1.Text) == 4)
NOTE: In the last option you can get an exception if the text in the textbox is not a number. So if you want to convert to integer than I would suggest:
int guessedNumber;
Int32.TryParse(textbox1.Text, out guessedNumber);
if(guessedNumber == 4)
You are trying to compare a string with an int.
You need to use if(textbox1.text == "4")
also note the double == for comparisons
The Text property is of type string and 4 is an int so the comparison results in a compile time error.
Use the following code to perform the check.
if (int.Parse(textbox1.Text) == 4)
{
// do something
}
If you're unsure whether the user is going to provide the input correctly or if you haven't set any validations on the model, then you should parse the input and then check whether the user entered 4. Here's the rextester link
//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5
using System;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
var input = "hello 4";
// var input = "4";
int number;
var isNumber = int.TryParse(input, out number);
if (isNumber)
{
if (number == 4)
{
Console.WriteLine("The Number is 4");
}
else
{
Console.WriteLine("The Number isn't 4");
}
}
else
{
Console.WriteLine("Not a valid number");
}
}
}
}
if(textbox1.Text == "4")
{
//Do Something
}
One way or another, you have to make sure both values are to make sure you are comparing two values "==" (not "=", unless u want to change the value) and that both values are same data type

Do loop practice?

static void Main(string[] args)
{
int output = 0;
int number = 0;
Console.WriteLine("Please input a number for it to be counted!");
bool conversion = int.TryParse(Console.ReadLine(), out output);
if( number >= 1000)
{
while (number <= output)
{
switch (conversion)
{
case true:
Console.Write(number + " ");
number += 2;
break;
case false:
Console.WriteLine("ERROR INVALID INPUT!");
break;
}
}
}
else
{
Console.WriteLine("APPLICATION ERROR: NUMBER MUST BE BELOW OR AT 1000 TO PREVENT OVERFLOW!");
}
string choice = Console.ReadLine();
do // Here is the beginning of the do code
{
Console.WriteLine("Do you want to continue - Yes or No");
if(choice.ToUpper() != "NO" && choice.ToUpper() != "NO");
{
Console.WriteLine("ERROR INVALID INPUT: Only input Yes or No!");
}
}while(choice.ToUpper() != "YES" && choice.ToUpper() != "NO");
}
}
}
This is a very simple application and is unfinished but what it does is you put in a number below or equal to 1000 and it counts up to it evenly. My only problem is with the do statement at the end of the code. Its unfinished but from what I've researched that do statement is completed what happens is if the user does not input yes or no it will show them that error and then ask again "do you want to go again" However because of this do statement I put in any number like 10 and it gives me the error saying its over 1000 and then goes on an infinite loop of saying "ERROR INVALID INPUT: ONLY INPUT YES OR NO!" How can I fix this?
Your if statement tests for NOT EQUAL to "no" twice, I assume you mean to check for not equal to "YES" and not equal to "NO"
Your infinite loop is because the condition checks the content of choice, but you never change the value of the variable within the do loop - only in the Console.ReadLine() immediately before the loop starts.
You should start the do loop before the code you want to be repeated. For instance, if your intent is that if the user types yes that the entire process repeats, you may be best served by creating a void function, say static void CountNumbers() { ... } that has all the code doing your input on how high to count, error handling, etc. Then you can use your do loop to easily repeat as much as the user wants, like this:
string choice = null;
do
{
CountNumbers();
// Your code here to ask if user wants to continue and readline to get the new choice
} while ( /* Existing condition */);
You have several issues in the code:
First, your condition checks that number is GREATER than or equal to 1000. Since you're entering 10, which is not >= 1000, then you get to the else statement. So you need to change your condition to:
if(number <= 1000)
Next, your condition in the do loop checks the same condition twice... you don't allow the user to enter "yes". You should modifiy the condition to include a check for "yes". Also, you need to remove the semi-colon from the end of that same if statement:
do
{
Console.WriteLine("Do you want to continue - Yes or No");
choice = Console.ReadLine();
if(choice.ToUpper() != "NO" && choice.ToUpper() != "NO");
{
Console.WriteLine("ERROR INVALID INPUT: Only input Yes or No!");
}
} while(choice.ToUpper() != "YES" && choice.ToUpper() != "NO");
One thing you also might consider is adding a method to get an integer from the user, since it is handy to wrap it in some validation:
public static int GetIntFromUser(string prompt,
string errorMessage = "Invalid entry. Please try again.")
{
int value;
while (true)
{
if (prompt != null) Console.Write(prompt);
if (int.TryParse(Console.ReadLine(), out value)) break;
if (errorMessage != null) Console.WriteLine(errorMessage);
}
return value;
}
Then, you can call this method when you need to get an int from the user. Here's a sample of how it could be used:
private static void GenericTester()
{
// This will flag that the user wants to quit
bool quit = false;
while(!quit)
{
// Get input from user
int userInput = GetIntFromUser("Please input a number to be counted: ");
int number = 0;
// Write out the numbers
if (userInput <= 1000)
{
while (number <= userInput)
{
Console.Write(number + " ");
number += 2;
}
}
else
{
Console.WriteLine("APPLICATION ERROR: NUMBER MUST BE BELOW " +
"OR AT 1000 TO PREVENT OVERFLOW!");
}
// See if they want to continue
while (true)
{
// Get user input
Console.Write("Do you want to continue - Yes or No: ");
string choice = Console.ReadLine();
// If they said 'No', set flag to quit and break out of this loop
if (choice.Equals("No", StringComparison.OrdinalIgnoreCase))
{
quit = true;
break;
}
// If they said 'Yes', just break out of this loop
if (choice.Equals("Yes", StringComparison.OrdinalIgnoreCase)) break;
// Otherwise, display an error message and let the loop continue
Console.WriteLine("ERROR INVALID INPUT: Only input Yes or No!");
}
}
}

In C#, how to check whether a string contains an integer?

I just want to know, whether a String variable contains a parsable positive integer value. I do NOT want to parse the value right now.
Currently I am doing:
int parsedId;
if (
(String.IsNullOrEmpty(myStringVariable) ||
(!uint.TryParse(myStringVariable, out parsedId))
)
{//..show error message}
This is ugly - How to be more concise?
Note: I know about extension methods, but I wonder if there is something built-in.
You could use char.IsDigit:
bool isIntString = "your string".All(char.IsDigit)
Will return true if the string is a number
bool containsInt = "your string".Any(char.IsDigit)
Will return true if the string contains a digit
Assuming you want to check that all characters in the string are digits, you could use the Enumerable.All Extension Method with the Char.IsDigit Method as follows:
bool allCharactersInStringAreDigits = myStringVariable.All(char.IsDigit);
Maybe this can help
string input = "hello123world";
bool isDigitPresent = input.Any(c => char.IsDigit(c));
answer from msdn.
You can check if string contains numbers only:
Regex.IsMatch(myStringVariable, #"^-?\d+$")
But number can be bigger than Int32.MaxValue or less than Int32.MinValue - you should keep that in mind.
Another option - create extension method and move ugly code there:
public static bool IsInteger(this string s)
{
if (String.IsNullOrEmpty(s))
return false;
int i;
return Int32.TryParse(s, out i);
}
That will make your code more clean:
if (myStringVariable.IsInteger())
// ...
This work for me.
("your string goes here").All(char.IsDigit)
Sorry, didn't quite get your question. So something like this?
str.ToCharArray().Any(char.IsDigit);
Or does the value have to be an integer completely, without any additional strings?
if(str.ToCharArray().All(char.IsDigit(c));
string text = Console.ReadLine();
bool isNumber = false;
for (int i = 0; i < text.Length; i++)
{
if (char.IsDigit(text[i]))
{
isNumber = true;
break;
}
}
if (isNumber)
{
Console.WriteLine("Text contains number.");
}
else
{
Console.WriteLine("Text doesn't contain number.");
}
Console.ReadKey();
Or Linq:
string text = Console.ReadLine();
bool isNumberOccurance =text.Any(letter => char.IsDigit(letter));
Console.WriteLine("{0}",isDigitPresent ? "Text contains number." : "Text doesn't contain number.");
Console.ReadKey();
The answer seems to be just no.
Although there are many good other answers, they either just hide the uglyness (which I did not ask for) or introduce new problems (edge cases).

Categories

Resources