这是我到目前为止,我需要将此字符串数组转换为整数数组,字符串数组看起来像这样
wholef[0] = "2 3 4";
wholef[1] = "1 3 4";
wholef[2] = "5 3 5";
wholef[3] = "4 5 6";
wholef[4] = "3 10 2";
这些值来自我读取的文本文件,但现在我需要将其转换为一个大整数数组,我试图使用拆分方法,但我不确定它是否适用于这种设置。如果有人能给我一个更好的方法它会很好但我只需要将它转换成一个整数数组,这就是我真正需要的。
for(int k = 0; k < fline; k++)
{
String[] items = wholef[k].replaceAll(" ", "").split(",");
int[] parsed = new int[wholef[k].length];
for (int i = 0; i < wholef[k].length; i++)
{
try
{
parsed[i] = Integer.parseInt(wholef[i]);
} catch (NumberFormatException nfe) {};
}
}
这是我现在使用的新代码,它非常接近因为我只得到一个错误
int q = 0;
for (String crtLine : wholef)
{
int[] parsed = new int[wholef.length];
String[] items = crtLine.split(" ");
for (String crtItem: items)
{
parsed[q++] = Integer.parse(crtItem);
}
}
错误就是这个 java:97:错误:找不到符号解析[q ++} = Integer.parse(crtItem); ^ symbol:方法解析(String) location:类Integer 1错误
答案 0 :(得分:4)
试试这个:
int i = 0;
for (String crtLine : wholef) {
String[] items = crtLine.split(" ");
for (String crtItem: items) {
parsed[i++] = Integer.parseInt(crtItem);
}
}
答案 1 :(得分:2)
这将获取你的字符串数组并将其转储到intwholef [n..total]; 如果您想将它放入2D数组或对象数组中,您还需要做一些额外的操作。然后,您可以执行一组对象,并将每组值作为属性。
String[] parts = wholef[0].split(" ");
int[] intwholef= new int[parts.length];
for(int n = 0; n < parts.length; n++) {
intwholef[n] = Integer.parseInt(parts[n]);
}