带有2个hasNext()的Java扫描程序

时间:2015-03-11 01:21:54

标签: java csv java.util.scanner reader

我想从CSV文件中恢复对象。我需要知道扫描仪是否有2个下一个值:scanner.hasNext()

问题是我的访问构造函数需要2个参数,我需要确保 我的csv文件中至少剩下2个。

这是相关代码:

    /**
 * method to restore a pet from a CSV file.  
 * @param fileName  the file to be used as input.  
 * @throws FileNotFoundException if the input file cannot be located
 * @throws IOException if there is a problem with the file
 * @throws DataFormatException if the input string is malformed
 */
public void fromCSV(final String fileName)
throws FileNotFoundException, IOException, DataFormatException
{
    FileReader inStream = new FileReader(fileName);
    BufferedReader in = new BufferedReader(inStream);
    String data = in.readLine();
    Scanner scan = new Scanner(data);
    scan.useDelimiter(",");
    this.setOwner(scan.next());
    this.setName(scan.next());
    while (scan.hasNext()) {
        Visit v = new Visit(scan.next(), scan.next());
        this.remember(v);
    }
    inStream.close();
}

提前致谢

2 个答案:

答案 0 :(得分:1)

直接解决我认为你问的问题:你可以在while循环中检查scan.hasNext()

public void fromCSV(final String fileName) throws FileNotFoundException, IOException, DataFormatException
{
    FileReader inStream = new FileReader(fileName);
    BufferedReader in = new BufferedReader(inStream);
    String data = in.readLine();
    Scanner scan = new Scanner(data);
    scan.useDelimiter(",");
    this.setOwner(scan.next());
    this.setName(scan.next());
    while (scan.hasNext()) {
        String first = scan.next();
        if(scan.hasNext()) {
            String second = scan.next();
            Visit v = new Visit(first, second);
            this.remember(v);
        }
    }
    inStream.close();
}

虽然我认为你在询问while循环中使用scan.hasNext(),但你也应该在this.setOwner(scan.next())this.setName(scan.next())之前进行检查。

在评论中,如Hovercraft Full Of Eels所建议的那样采取另一种解决问题的办法可能会更好。更好的是,由于这是一个CSV文件,因此您可以使用Commons CSVopencsv等库来省去很多麻烦。

答案 1 :(得分:1)

hasNext()也可以采用一种模式,这提供了一种很好的检查方法:

String pattern = ".*,.*";
while (scan.hasNext(pattern)) {
  ...
}