Java parseInteger 抛出错误

标签 java parseint

我的测试器类中有以下代码片段。

     FileReader freader=new FileReader(filename);
     BufferedReader inputFile=new BufferedReader(freader);
     int numScores = 0;
     String playerType = "";
     String nameHome = "";
     String playerName = "";
     String home = "";
     String location = "";
     int score = 0;
     String date = "";
     double courseRating = 0;
     int courseSlope = 0;

     ArrayList<Player> players = new ArrayList<Player>();

     while (inputFile.read()!= -1) {
        numScores = Integer.parseInt(inputFile.readLine()); 
        playerType = inputFile.readLine();
        nameHome = inputFile.readLine();
        StringTokenizer st = new StringTokenizer(nameHome,",");
        playerName = st.nextToken();
        home = st.nextToken();

程序可以编译,但是当测试器运行时,我收到以下输出错误。

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at PlayerTest.main(PlayerTest.java:34)

我尝试对此进行研究,但我发现,当它更改从数据文件读取的字符串并将其转换为 int 时,可能存在空格。我尝试直接读入字符串,修剪字符串,然后转换为 int,但出现了相同的错误。

这是替换 numScores = Integer.parseInt(inputFile.readLine()); 的代码

        tempScores = inputFile.readLine();
           tempScores.trim();
           System.out.println(tempScores);
           numScores = Integer.parseInt(tempScores);

感谢任何帮助。

*编辑以显示示例数据 文件中的示例数据

3
B
James Smith, Strikers
FWB Bowling, 112,09/22/2012
White Sands, 142,09/24/2012
Cordova Lanes,203,09/24/2012

最佳答案

您的文件可能包含空行。这些被读取为“”,因此无法转换为 int。

此外,您有可能通过 while 循环头中的 read 语句读取每行的第一个字符,从而在 readline 命令中忽略它。那么长度为 1 的数字(如“1”)将成为空行。

无论如何,循环的构造都是一个错误。

关于Java parseInteger 抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35466752/

相关文章:

java - 偶尔出现 HibernateException

java.util.ConcurrentModificationException 与 HashSet

Java:从 char 解析 int 值

javascript - 尝试从货币字符串中删除美元符号以将字符串转换为整数

java - java中如何将多个字符串解析为int

java - 如何捕获 parseInt 抛出的 NumberFormatException

java - 从字符串列表中提取并排序顶部 int 值

java - 编写一个java程序来读取长字符串(使用流)并将输出写入文件?

java - 如何通过 UCanAccess 创建一个具有对另一个表的两个外键引用的表?

java - 从文件中读取前 5 行,然后读取其余行