gpt4 book ai didi

java - 将 String 转换为 Integer 时出现 NumberFormatException

转载 作者:行者123 更新时间:2023-11-29 03:28:59 24 4
gpt4 key购买 nike

我想将字符串数组转换为整数。我写了这个,但 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 不喜欢这些行。我想在这里将字符串数组转换为整数。然后我会将整数用于其他逻辑。

    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)

知道哪里出了问题吗?

最佳答案

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

所以你试图解析的当前字符串在行中是空的

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

不可能从一个空字符串中得到一个整数值,这就是exception所说的。

你能做的只是在解析之前检查String是否为空。

关于java - 将 String 转换为 Integer 时出现 NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19420265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com