0

我想从 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();
}

提前致谢

4

2 回答 2

1

直接解决我认为您要问的问题:您可以检查scan.hasNext()while 循环内部。

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();
}

尽管我认为您是在询问scan.hasNext()while 循环中的使用,但您还应该在 and 之前进行this.setOwner(scan.next())检查this.setName(scan.next())

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

于 2015-03-11T01:31:22.927 回答
1

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

String pattern = ".*,.*";
while (scan.hasNext(pattern)) {
  ...
}
于 2015-03-11T01:40:25.350 回答