将字符串与另一个字符串进行比较

时间:2015-07-07 23:34:25

标签: c# string if-statement

我有一个用户对其年龄的回复,存储为int age;。然后我要求用户将他们的年龄除以某个数字,然后他们将这个数字输入我的控制台。该号码存储为int rep;。从那里,我想询问int rep;是偶数还是奇数。我意识到你不能在if ()语句中使用字符串。但是,我无法正确地制定我的问题,以便在网上找到解决方案/帖子,这将有助于我了解如何检查我存储为字符串的用户输入是否可以与答案进行比较我预计。

总结:字符串的if ()是否有等效的语法?

//Second task
int age;
int rep;


Console.WriteLine ("How old are you? ");
age = Convert.ToInt32 (Console.ReadLine ());
Console.WriteLine ("What is the your age divided by your first number submitted in the previous question? ");
rep = Convert.ToInt32 (Console.ReadLine ());
if (rep == age / num01 ) {
    Console.WriteLine ("That is correct. Proceed to the next question. ");
} else
{
    Console.WriteLine ("That is incorrect. Start over. ");
}
Console.WriteLine ();

//Third task
string ans;

Console.WriteLine ("Is your answer to the previous question an even or odd number? ");
ans = Console.ReadLine ();
if (rep % 2 == 0 && ans == even)
{
    Console.WriteLine ("That is correct. ");
}
if (rep % 2 == 1 && ans == odd) 
{
    Console.WriteLine ("That is correct. ");
}   

2 个答案:

答案 0 :(得分:2)

在你的情况下我会改变

ans = Console.ReadLine();

对此。

ans = Console.ReadLine().ToLower();

然后将您的ITE改为此。

if (rep % 2 == 0 && ans == "even") {//code here.}
else if (ans == "odd") {//code here.} // This should also be else if not just if. With it being else if the extra check rep % 2 == 1 is not needed.

或者为了更好的字符串比较,你应该这样做。

ans = Console.ReadLine();
if (rep % 2 == 0 && ans.Equals("even", StringComparison.OrdinalIgnoreCase)) {//code here.}
else if (ans == ans.Equals("odd", StringComparison.OrdinalIgnoreCase)) {//code here.} // This should also be else if not just if. With it being else if the extra check rep % 2 == 1 is not needed. 

以上将检查比较并忽略字符串的大小写,因此您不需要使用ToLower,并且不应出现使用==的字符串比较问题。

感谢Alexei Levenkov指出这一点。

您还可以查看此字符串,以便将来参考字符串比较。 https://msdn.microsoft.com/en-us/library/system.stringcomparison(v=vs.110).aspx

答案 1 :(得分:0)

https://msdn.microsoft.com/en-us/library/system.string.op_equality%28v=vs.110%29.aspx

==运算符适用于字符串,因此以下是使代码工作所需的修改

//Second task
int age;
int rep;


Console.WriteLine ("How old are you? ");
age = Convert.ToInt32 (Console.ReadLine ());
Console.WriteLine ("What is the your age divided by your first number submitted in the previous question? ");
rep = Convert.ToInt32 (Console.ReadLine ());
if (rep == age / num01 ) {
    Console.WriteLine ("That is correct. Proceed to the next question. ");
} 
else
{
    Console.WriteLine ("That is incorrect. Start over. ");
}
Console.WriteLine ();

//Third task
string ans;

Console.WriteLine ("Is your answer to the previous question an even or odd number? ");
ans = Console.ReadLine ();
//change 1
if (rep % 2 == 0 && ans == "even")
{
   Console.WriteLine ("That is correct. ");
}
//change2
if (rep % 2 == 1 && ans == "odd") 
{
    Console.WriteLine ("That is correct. ");
}  
相关问题