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

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

Related

Check answer button has incorrect input string format

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;

How to compare whether two strings are identical?

So I'm doing this years Advent of Code and I'm stuck on the second day, part 2.
You are given inputs which look like this:
"1-3 c: caaasa"
You have to check how many passwords are valid due to the policy like,
in above example:
letter c has to be in position 1 OR 3 in the string caaasa. If
yes, the password is valid.
I've broken down that string to different sections, and now I try to compare a string "znak" which contains that given letter to a letter on position zakresmin and zakresmax in string "passdiv"
Yet, everytime it returns False, so it doesn't add up to the count of passwords.
I tried using Equals() and CompareTo(), but they don't seem to work.
How can I modify my code so it returns proper values?
var iloschasel = 0;
using (StreamReader sr = new StreamReader(#"C:\Users\Wurf\Desktop\text.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] linia = line.Split(" ");
string zakres = linia[0];
string[] zakresy = zakres.Split("-");
int zakresmin = Convert.ToInt32(zakresy[0]);
int zakresmax = Convert.ToInt32(zakresy[1]);
string znak = (linia[1].Replace(":", "")).Trim();
var suma = Regex.Matches(linia[2], znak);
string passdiv = linia[2];
if(passdiv[zakresmin].Equals(znak) || passdiv[zakresmax - 1].Equals(znak))
{
iloschasel += 1;
}
}
}
Console.WriteLine(iloschasel);
As mentioned, when you call Equals on two different types you are playing a game of chance with how the actual types are implemented. In this case you lose. Strings and chars will never have an equivalence or the same reference.
I believe the compiler or resharper would give you a warning alerting you that neither type derive from string and char
However, I was bored enough to give an alternate solution
public static bool IsValid(string input)
{
var match = Regex.Match(input, #"(\d)-(\d) (\S): (.*)");
if(!match.Success)
throw new ArgumentException( $"Invalid format : {input}",nameof(input));
var first = int.Parse(match.Groups[1].Value);
var second = int.Parse(match.Groups[2].Value);
var c = char.Parse(match.Groups[3].Value);
var password = match.Groups[4].Value;
return password[first-1] == c && password[second-1] == c;
}
Test
Console.WriteLine($"Is Valid = {IsValid("1-3 c: caaasa")}");
Console.WriteLine($"Is Valid = {IsValid("1-3 c: cacaasa")}");
Output
Is Valid = False
Is Valid = True
Note : this is not meant to be a complete bullet-proof solution. Just a novel elegant way to solve your problem
Your problem is that you are comparing a string to a char
var match = "c" == 'c';
Will give a compile error because they are different data types
var match = "c".Equals('c');
will let you compile, but will always return false because a char will never equal a string. You have to turn the char into a string or visa versa for the check to work
var match = "c"[0] == 'c';
So in your if statement, if you fix the check to compare strings with strings or chars with chars you should get some positive results. And also fix your indexing issue to decide if you want a 0 based index or a 1 based index with zakresmin and max
Also as a side note, it can be helpful to step through your code line by line in debug mode, to find out which line isn't behaving like you expect it to. In your case debugging would have helped you zero in on the if statement as a starting point to fixing things.
So it turns out (if I understand that correctly) that a compared element of the string passdiv was a char which I tried to compare to znak which was a string. I added ToString() to my code and it works well. Also fixed the range of zakresmin by subtracting 1 so it works properly.
if((passdiv[zakresmin - 1].ToString() == znak && passdiv[zakresmax - 1].ToString() != znak) || (passdiv[zakresmin - 1].ToString() != znak && passdiv[zakresmax - 1].ToString() == znak))
{
iloschasel += 1;
}

How do I Limit C# ReadKey entries?

I've been trying to find a way to do this but not had much luck so far.
Basically what I'm trying to do is limit the entries from the user so they can only enter 1 letter and 1 number using the Console.Readkey. So, for example, A1, E5, J9 etc. I want to avoid them entering like 55 or EE as this causes an error in my code. Is there an easy way to achieve this?
You need to write your own logic like you will check on every input value contains at least 1 number and 1 letter is true else false:
string value = Console.ReadLine();
//you can also check value.length and redirect if length greater than 2
if (value.Length > 2)
{
Console.WriteLine("Please enter correct value");
return;
}
if (value.Contains("Your Number"))
{
if (value.Contains("Your Letter"))
{
//your code goes here
}
else
{
Console.WriteLine("Please Enter Correct Value");
}
}
else
{
Console.WriteLine("Please Enter Correct Value");
}
This uses a GetChar method which requires that you pass a function to check whether the input is a character or a number. It won't allow you so proceed until a valid entry has been made.
using System;
class Program {
public static void Main (string[] args) {
string value = string.Empty;
// Get a character, using char.IsLetter as the checking function...
GetChar(ref value, char.IsLetter);
// Get a number, using char.isNumber as the checking function...
GetChar(ref value, char.IsNumber);
Console.WriteLine($"\nValue: {value.ToUpper()}");
}
// Get a character and append it to the referenced string.
// check requires that you pass a function reference for the required check.
public static void GetChar(ref string value, Func<char, bool> check) {
// Loop until the check passes.
while(true) {
char key = Console.ReadKey(true).KeyChar;
// If check passes...
if(check(key)) {
// Append the value
value += key.ToString().ToUpper();
// Print it...
Console.Write(key.ToString().ToUpper());
// Break out of the loop.
break;
}
}
}
}

how to check the if condition with string and integer

I want to get result of a value with if condition.
i have get some value in xml file.
now what I want is
if I have a variable "a" here i have assigned some values by using dataset.
and i have another variable "b" is assigned value from xml file.
for example
int a=25;
string b=">10"
now I want to check the condition if condition with out ">" because the symbol present in b variable. I dont know how to check this condition can anybody explain me how to acheive this.
I tried like this but not working
if(a+b)
You can use the DataTable.Compute-"trick" to evaulate such expressions:
int a = 25;
string b = ">10";
bool isTrue = (bool)new DataTable().Compute($"{a}{b}", null); // true
What is supported you can read at the DataColumn.Expression remarks.
if the condition is 1!=10, how to use not equal in this code .this
condition is not working what should i do.
As the documentation tells you that is not valid syntax, you have to use <> (look at operators). So a simple approach would be either to use <> in the first place or replace them:
b = b.Replace("!=", "<>");
You can have some function to remove non numeric characters:
public int Parse(string x)
{
x = Regex.Replace(x, "[^0-9.]", "");
int result = 0;
int.TryParse(x , out result);
return result;
}
If its always a number with a symbol then:
symbol = b[0];
int bval = int.Parse(b.Substring(1))
And considering your comment for comparison you can do:
if((symbol=='>'&&a>b)||
(symbol=='='&&a==b)||
(symbol=='<'&&a<b)
){
//do your magic here
}
Of course you may need only one of < = > or you may need to have separate if conditions for each, what ever suits your needs, but I just wanted to give the idea.
I tried like this
if (b.Contains(">")) {
b = b.Replace(">", "");
if (a >Convert.ToInt32(b))
{
Console.WriteLine("value is less");
}
else
{
Console.WriteLine("value is Greater");
}
}
similarly all the symbols
First separate symbol from b:
string symbol = b[0].ToString();
string numberString = b.SubString(1);
int number = int.Parse(numberString);
Now use switch to get operation for symbol and compare:
bool result = false;
switch (symbol)
{
case ">":
if (a > number)
{
result = true;
}
break;
}
EDIT: Changed symbol declaration to avoid error: "cannot implicit convert type char to string"

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

Categories

Resources