Java 具有 2 个 hasNext() 的扫描器

Java scanner with 2 hasNext()

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

问题是我的访问构造函数有两个参数,我需要确保 我的 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();
}

提前致谢

直接解决我认为您要问的问题:您可以在 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 CSV or opencsv.

这样的库来省去很多麻烦。

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

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