[NumberFormatException读取文件时

问题描述 投票:0回答:1

我正在尝试读取一个包含有关电影(电影ID,标题,演员和剧组)信息的文件,并试图通过解析将文件中的某个子字符串存储为int movieID。但是,我收到一个错误:线程“ main”中的异常java.lang.NumberFormatException:对于输入字符串:“” @行movieID = Integer.parseInt(movieLine.substring(0,index1-1);

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;

public class Assignment2 {

    public static void main(String[] args) throws FileNotFoundException {
        File movieFile = new File("tmdb_5000_credits.csv");
        Scanner scan = new Scanner(movieFile);
        String movieLine, actorName;
        int movieID, index1, index2;
        ArrayList<MovieCast> list = new ArrayList<>();
        MovieCast listObj;
        scan.nextLine(); // skip first line (movie_id, title, cast, crew)
        while(scan.hasNext()) {
            movieLine = scan.nextLine();
            if(!movieLine.isEmpty()) {
                index1 = movieLine.indexOf(',');
//              System.out.println("Index was " + index1 + " String was " + movieLine);
                movieID = Integer.parseInt(movieLine.substring(0, index1 - 1));
                index1 = movieLine.indexOf("cast_id"); // in case movie contains name
                if(index1 > -1) {
                    index1 = movieLine.indexOf("name", index1);
                    index1 += 7;
                    index2 = movieLine.indexOf(',', index1);
                    actorName = movieLine.substring(index1, index2 - 2);
                    listObj = new MovieCast(movieID, actorName);
                    list.add(listObj);
                }
            }
        }

    }

}

我已将大多数代码放在if语句内的while循环中,该语句检查该行是否为空,但是,它似乎无法解决问题。还有什么可能导致此问题?这是文件的链接:https://sabercathost.com/dQch/tmdb_5000_credits.csv

java file parsing exception numberformatexception
1个回答
0
投票

这是给出异常的parseInt方法。

两种可能性:在CSV中,此行/列没有匹配的数据。因为错误表明有一个空字符串:NumberFormatException: For input string: ""

如果movieId可以为空,则必须使用非Exception方法。

例如,您可以使用tryParse方法代替,请参见this线程

© www.soinside.com 2019 - 2024. All rights reserved.