【发布时间】:2014-10-15 15:18:19
【问题描述】:
我偶然发现了这个website,我正在尝试测试这个想法,我不懂Java,所以我尝试将它转换为C#。一切似乎都微不足道,但在执行示例时我遇到了一些异常。
我想这里一定是我做错了什么。产生该异常的方法如下:
static void setSolution(String newSolution)
{
solution = new byte[newSolution.length()];
// Loop through each character of our string and save it in our byte
// array
for (int i = 0; i < newSolution.length(); i++){
String character = newSolution.substring(i, i + 1);
if (character.contains("0") || character.contains("1")){
solution[i] = Byte.parseByte(character);
} else {
solution[i] = 0;
}
}
}
这是我基于 C# 的方法:
public static void SetSolution(string newSolution)
{
solution = new byte[newSolution.Length];
// Loop through each character of our string and save it in our byte
// array
for (int i = 0; i < newSolution.Length; i++)
{
string character = newSolution.Substring(i, i + 1);
if (character.Contains("0") || character.Contains("1"))
{
solution[i] = Byte.Parse(character);
}
else
{
solution[i] = 0;
}
}
}
我是否正确转换它?因为将例如 1000 转换为字节是没有意义的!因为它是静态的,所以字符串保留了它的旧值,因此在第 4 次迭代中它会吐出一个OverFlow Exception:
“System.OverflowException”类型的未处理异常发生在 mscorlib.dll
附加信息:对于 无符号字节。
我也试过了
solution[i] = Convert.ToByte(newSolution[i]);
这似乎又不是。
编辑
这是输入字符串:
"1111000000000000000000000000000000000000000000000000000000001111"
【问题讨论】:
-
你试过隐式转换吗?
solution[i] = (byte) character;? -
我也不明白,如果它包含0,您试图将其设置为0,如果它包含1,则将其设置为1,如果不包含则设置为0?为什么你不能把它改成:如果它包含 1,则将其设为 1。否则,将其设为 0。
-
你输入的字符串是什么?
-
您确定 Java 版本有效吗?
i+1当i == newSolution.length - 1越界时。 -
比较 java 和 C# 的子字符串函数,它们不会将 1 转换为 1。
标签: java c# code-conversion