簡體   English   中英

將一個字符串與另一個字符串進行比較

[英]Comparing a string to another string

我將用戶關於其年齡的回復存儲為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. ");
}   

你的情況我會改變

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

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. ");
}  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM