1

我想将字符串数组转换为整数。我写了这个,但是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(",");

日食不喜欢这些行。我想在这里将字符串数组转换为整数。然后我会将整数用于其他逻辑。

    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) 

有什么想法有什么问题吗?

4

1 回答 1

5
 java.lang.NumberFormatException: For input string: ""   

因此,您尝试解析的当前字符串在该行中为空

  result[i] = Integer.parseInt(arr[i].trim());

从空字符串中获取整数值是不可能的,这就是说的exception

你能做的只是检查它String之前的空虚parsing

于 2013-10-17T07:05:40.700 回答