将字符串数组转换为int数组''System.FormatException'
我尝试将data1字符串数组转换为int数组结束可能还有一些其他解决方案用于此任务,但如果可能,我想使其工作。将字符串数组转换为int数组''System.FormatException'
问题是当我开始问题时,它得到了一个停止并给我下面的问题:mscorlib.dll中发生类型'System.FormatException'的未处理的异常“ 也int.parse同样的问题。
static int[] data()
{
StreamReader house = new StreamReader("text.txt");
while (!house.EndOfStream)
{
s = house.ReadLine();
Console.WriteLine(s);
}
string[] data1 = s.Split(' ');
int[] database = new int[(data1.Length)];
for (int j = 0; j < data1.Length; j++)
{
database[j] = Convert.ToInt32(data1[j]);//Program stops here
}
return database;
}
的text.txt看起来像这样(数字用空格分隔““):
6 1 1
10 5 10
20 10 20
35 5 15
45 5 5
60 10 25
75 5 10
谢谢您的帮助!
您可以使用Int32.TryParse。 但是,如果转换失败,您的数组项目超出预期。因此,最好使用一个List。而且,您仅对文件的最后一行执行转换。 '{'位于错误位置。最后但并非最不重要的,您应该Disponse()流读取器对象。
static int[] data()
{
List<int> database = new List<int>();
StreamReader house = new StreamReader("text.txt");
while (!house.EndOfStream)
{
s = house.ReadLine();
Console.WriteLine(s);
string[] data1 = s.Split(' ');
for (int j = 0; j < data1.Length; j++)
{
int value;
if (Int32.TryParse(data1[j], out value))
database.Add(value));
}
}
house.Dispose();
return database.ToArray();
}
你试过int Integer.parseInt(string)
?
database[j] = Integer.parseInt(data1[j]);//Program stops here
另外,我会仔细什么这些内容切碎了检查字符串(例如,具有穆斯特在新行字符,是最后一行空白......),所以显示出来的另一个环绕性格,喜欢“或[] ...
'Integer.parseInt'? o.O这不是Java方法吗? – 2014-11-23 15:00:02
哎呀,我的错误,@SonerGönül – Heimdall 2014-11-23 16:44:06
大概一个空字符串进入你的分裂字符串数组
尝试做分割时定义StringSplitOptions
:
string[] data1 = s.Split(' ', StringSplitOptions.RemoveEmptyEntries);
您还可以检查循环中的空字符串:
for (int j = 0; j < data1.Length; j++)
{
if (string.IsNullOrWhitespace(data1[j])
continue;
database[j] = Convert.ToInt32(data1[j]);//Program stops here
}
当你调试你的代码时'data1 [j]'的值是多少?这显然不是一个有效的整数。这个'''不会只包含你的最后一行? – 2014-11-23 14:50:20