[英]If statement not working C#
我不確定我是否真的很累,錯過了一些明顯的東西,或者我的程序出了什么問題。 基本上我的if語句條件不起作用。
public bool check(string nextvaluebinary)
{
bool test = true;
for (int i = -1; i < 8; ++i)
{
i++;
System.Console.WriteLine(nextvaluebinary[i] + " " + nextvaluebinary[i + 1]);
if (nextvaluebinary[i] == 1)
{
System.Console.WriteLine("Activated");
if (nextvaluebinary[i + 1] == 0)
{
test = false;
System.Console.WriteLine("false");
}
}
else
{
test = true;
}
if (test == false)
{
break;
}
}
return test;
}
我正在傳遞字符串0001010110並獲得輸出:
0 0
0 1
0 1
0 1
1 0
但即使最后一個是“1 0”,也沒有“激活”或“假”。 再次抱歉,如果這是一個愚蠢的問題,任何見解或幫助將不勝感激。
你將char與int進行比較。 你正在嘗試的檢查帶有與你想要完成的完全不同的含義。 您需要檢查它是否等於'1'或首先將char轉換為int,以便進行數值比較。
if (nextvaluebinary[i] == '1')
由於nextvaluebinary
是一個String
,因此只有當該字符串具有空字符,即'\\0'
,此比較才會成功:
if (nextvaluebinary[i + 1] == 0)
看起來你正在尋找一個零位字符,所以你應該寫
if (nextvaluebinary[i + 1] == '0')
Equals與char一起使用。 所以這將使用char代碼。
用這個
public static bool check(string nextvaluebinary)
{
bool test = true;
for (int i = -1; i < 8; ++i)
{
i++;
System.Console.WriteLine(nextvaluebinary[i] + " " + nextvaluebinary[i + 1]);
if (nextvaluebinary[i] == '1')
{
System.Console.WriteLine("Activated");
if (nextvaluebinary[i + 1] == '0')
{
test = false;
System.Console.WriteLine("false");
}
}
else
{
test = true;
}
if (test == false)
{
break;
}
}
return test;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.