[英]Compare string to 2 other strings
所以我有這個代碼部分:
private int checkErrors() {
int error = 0;
if (!(nether.Text.Equals("true"))) { error += 1; }
if (!(nether.Text.Equals("false"))) { error += 1; }
if (!(fly.Text.Equals("true"))) { error += 1; }
if (!(fly.Text.Equals("false"))) { error += 1; }
if (!(achivments.Text.Equals("true"))) { error += 1; }
if (!(achivments.Text.Equals("false"))) { error += 1; }
if (!(whitelist.Text.Equals("true"))) { error += 1; }
if (!(whitelist.Text.Equals("false"))) { error += 1; }
if (!(pvp.Text.Equals("true"))) { error += 1; }
if (!(pvp.Text.Equals("false"))) { error += 1; }
if (!(commandBlock.Text.Equals("true"))) { error += 1; }
if (!(commandBlock.Text.Equals("false"))) { error += 1; }
if (!(spawnMonster.Text.Equals("true"))) { error += 1; }
if (!(spawnMonster.Text.Equals("false")) { error += 1; }
return error;
}
但無論如何,它都會使我得到'error = 7'
因為當一個陳述為真時,另一個則為假,所以我的問題是:
有沒有辦法將2個字符串與第三個字符串進行比較?
另一個示例:如果用戶userInput
不等於"a"
或"b"
,則我具有字符串userInput
並想要執行error += 1;
!
我懷疑您正在嘗試查找不是“ true” 且不是“ false”的情況。 所以像這樣:
if (spawnMonster.Text != "true" && spawnMonster.Text != "false")
{
error++;
}
或者,只表達一次條件,並將其應用於所有字符串:
var strings = new[] { nether.Text, fly.Text, achivments.Text, whitelist.Text
pvp.Text, commandBlock.Text, spawnMonster.Text };
return strings.Count(t => t != "true" && t != "false");
僅帶有兩個子句:
if (!nether.Text.Equals("true") && !nether.Text.Equals("false")) { error += 1; }
您可以使用的另一種方法是創建一個接受2個參數的函數。 一個參數將是userInput,另一個參數將是userInput不應包含的值的數組。 它將返回1或0。
例:
public int isBadValue(string userInput, string[] goodValues){
if(Array.IndexOf(userInput) > -1){
return 0;
}
return 1;
}
在您的代碼中,您可以執行以下操作:
string[] goodValues = {"a", "b"};
error += isBadValue("s", goodValues);
您可以輕松添加更多好的值,該函數將能夠處理它。 不知道是否會根據輸入字段更改好的值,這就是為什么我沒有在isBadValue函數中包括它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.