C# 返回错误的整数值
C# Returning Wrong Integer Value
我正在尝试 return 基于用户输入的索引,输入只有 2 个字符,例如 a1、b2、c3...
public int returnInt(string x)
{
if (x == "a")
return 0;
else if (x == "b")
return 1;
else if (x == "c")
return 2;
else if (x == "d")
return 3;
else if (x == "e")
return 4;
else if (x == "f")
return 5;
else if (x == "g")
return 6;
else if (x == "h")
return 7;
else if (x == "1")
return 0;
else if (x == "2")
return 1;
else if (x == "3")
return 2;
else if (x == "4")
return 3;
else if (x == "5")
return 4;
else if (x == "6")
return 5;
else if (x == "7")
return 6;
else if (x == "8")
return 7;
return 0;
}
And this is where i use the method:
var toMove = myButtonArray[returnInt(totxt.Text.Substring(0)), returnInt(totxt.Text.Substring(1))];
the method works fine for the second substring, but it doesn't work for the first substring(0). Can anyone help me about this? When I type a1, program should return to 1 and 1 but it only returns 0 for the first substring.
让我们用单个字符,而不是字符串s:
public int returnInt(char x) =>
x >= 'a' && x <= 'h' ? x - 'a'
: x >= '1' && x <= '8' ? x - '1'
: 0;
然后你可以输入:
var toMove = myButtonArray[returnInt(totxt.Text[0]), returnInt(totxt.Text[1])];
请注意,我们得到的是 0th 和 1st char
,而不是 string
由于您的输入字符串始终只有 2 个字符,并且您想将它们用作二维数组的索引,因此您需要将代码更改为以下内容:
var toMove = myButtonArray[returnInt(totxt.Text.Substring(0,1)),
returnInt(totxt.Text.Substring(1,1))];
这样你就是说 String.Substring 函数一次 return 1 个字符,并提到起始索引作为第一个输入参数。
我正在尝试 return 基于用户输入的索引,输入只有 2 个字符,例如 a1、b2、c3...
public int returnInt(string x)
{
if (x == "a")
return 0;
else if (x == "b")
return 1;
else if (x == "c")
return 2;
else if (x == "d")
return 3;
else if (x == "e")
return 4;
else if (x == "f")
return 5;
else if (x == "g")
return 6;
else if (x == "h")
return 7;
else if (x == "1")
return 0;
else if (x == "2")
return 1;
else if (x == "3")
return 2;
else if (x == "4")
return 3;
else if (x == "5")
return 4;
else if (x == "6")
return 5;
else if (x == "7")
return 6;
else if (x == "8")
return 7;
return 0;
}
And this is where i use the method:
var toMove = myButtonArray[returnInt(totxt.Text.Substring(0)), returnInt(totxt.Text.Substring(1))];
the method works fine for the second substring, but it doesn't work for the first substring(0). Can anyone help me about this? When I type a1, program should return to 1 and 1 but it only returns 0 for the first substring.
让我们用单个字符,而不是字符串s:
public int returnInt(char x) =>
x >= 'a' && x <= 'h' ? x - 'a'
: x >= '1' && x <= '8' ? x - '1'
: 0;
然后你可以输入:
var toMove = myButtonArray[returnInt(totxt.Text[0]), returnInt(totxt.Text[1])];
请注意,我们得到的是 0th 和 1st char
,而不是 string
由于您的输入字符串始终只有 2 个字符,并且您想将它们用作二维数组的索引,因此您需要将代码更改为以下内容:
var toMove = myButtonArray[returnInt(totxt.Text.Substring(0,1)),
returnInt(totxt.Text.Substring(1,1))];
这样你就是说 String.Substring 函数一次 return 1 个字符,并提到起始索引作为第一个输入参数。