我想将String数组转换为Integer。我写了这个,但是eclipse返回错误:
以下是代码:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("array_list.csv"));
String everything = "";
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append('\n');
line = br.readLine();
}
everything = sb.toString();
} finally {
br.close();
}
int firstArrLenght = everything.indexOf("]");
int secondArrStartIndex = everything.lastIndexOf("[") + 1;
int secondArrLenght = everything.lastIndexOf("]") - secondArrStartIndex;
String[] firstStrArr = everything.substring(1, firstArrLenght).split(",");
String[] secondStrArr = everything.substring(secondArrStartIndex, secondArrLenght).split(",");
eclipse并不喜欢这些行。我想将String Array转换为Integer。然后我将使用int来表示其他逻辑。
int[] firstArray = transformToInt(firstStrArr);
int[] secondArray = transformToInt(secondStrArr);
}
private static int[] transformToInt(String[] arr) {
int[] result = new int[arr.length];
for(int i = 0; i < arr.length; i++) {
result[i] = Integer.parseInt(arr[i].trim());
}
return result;
}
异常堆栈跟踪:
Exception in thread "main" java.lang.NumberFormatException:
For input string: "" at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Java.transformToInt(Java.java:38)
at Java.main(Java.java:30)
任何想法有什么不对?
答案 0 :(得分:4)
java.lang.NumberFormatException: For input string: ""
因此,您尝试解析的当前字符串在行
中为空 result[i] = Integer.parseInt(arr[i].trim());
从空字符串中获取整数值是不可能的,这就是exception
所说的。
您可以做的只是在String
之前检查parsing
的空虚。