Rik*_*ika 2 c# java code-conversion
我偶然发现了这个网站,我正在尝试测试这个想法,我不知道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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我基于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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正确地转换它吗?因为将1000转换为字节没有意义!因为它是静态的,所以字符串保留了它的旧值,因此在第4次迭代中它会吐出OverFlow Exception:
mscorlib.dll中发生了未处理的"System.OverflowException"类型异常
附加信息:对于无符号字节,值太大或太小.
我也试过了
solution[i] = Convert.ToByte(newSolution[i]);
Run Code Online (Sandbox Code Playgroud)
这似乎不是它.
编辑
这是输入字符串:
"1111000000000000000000000000000000000000000000000000000000001111"
Run Code Online (Sandbox Code Playgroud)
Java和C#之间的子串函数不一样:
Java的:
public String substring(int beginIndex, int endIndex)
Run Code Online (Sandbox Code Playgroud)
C#:
public string Substring(int startIndex, int length)
Run Code Online (Sandbox Code Playgroud)
转换此行以反映它在Java中所做的事情.
相当于:
public static void SetSolution(string newSolution)
{
solution = new sbyte[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, 1);
if (character.Contains("0") || character.Contains("1"))
{
solution[i] = SByte.Parse(character);
}
else
{
solution[i] = 0;
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是如何转换为C#,我个人会使用Linq:
public static void SetSolution(string newSolution)
{
solution = newSolution.Select(c => c == '1' ? (byte)1 : (byte)0).ToArray();
}
Run Code Online (Sandbox Code Playgroud)
我相信上面的代码应该在功能上等同于你的java片段,因为基本上除了'1'之外的所有字符都转换为0.
| 归档时间: |
|
| 查看次数: |
322 次 |
| 最近记录: |