gpt4 book ai didi

java - 将 sLine 字符串解析为整数时出错

转载 作者:行者123 更新时间:2023-12-02 05:14:00 25 4
gpt4 key购买 nike

这段代码只是一个文件读取器,它没有显示任何错误,但是当我运行它时,这一行似乎出现错误: int temp2 = Integer.parseInt(temp[x]);

为什么这个变量似乎无法解析为整数?

public void loadRecordTimes(){

//get each time from the text file
try{
File f = new File ("Times.txt");
//appends content to file
FileReader fr = new FileReader(f);
//bufferedwriter writer give better performance
BufferedReader br = new BufferedReader(fr);

//reads a line from the text file
String sLine = br.readLine();

//as long as something was read from the file, it will keep running
while (sLine != null){
//take the line that was read and split it based on on the comma
String[] temp = sLine.split(",");

for (int x = 0; sLine != null; x++){

System.out.println(temp[x]);

int temp2 = Integer.parseInt(temp[x]);
//adds recorded times from content file to array
recordTimes.add(temp2);

}

sLine = br.readLine();
}

br.close();
fr.close();

}

catch(IOException e){

System.out.println("Exception occured:");
e.printStackTrace();

}

}

这是我的 IDE 给我的错误消息(如果有帮助的话):

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at GlobeTrotter.loadRecordTimes(GlobeTrotter.java:912)
at GlobeTrotter.<init>(GlobeTrotter.java:54)
at GlobeTrotter$22.run(GlobeTrotter.java:1460)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

最佳答案

要修复 NumberFormatException,只需删除文本文件末尾的所有空格即可。当您尝试解析末尾的空格或换行符时,会引发异常。

执行此操作后,该行代码中出现另一个错误:

for (int x = 0; sLine != null; x++){ 

sLine != null 不是正确的停止条件,因为当编译器到达这一行时它始终为 true。因此,它在到达数组末尾后继续,并将抛出 IndexOutOfBoundsException

要修复该问题,请将其替换为:

for (int x = 0; x < temp.length; x++){  

关于java - 将 sLine 字符串解析为整数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56308501/

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