带2 hasNext()的Java扫描程序

带2 hasNext()的Java扫描程序,java,csv,java.util.scanner,reader,Java,Csv,Java.util.scanner,Reader,我想从CSV文件还原一个对象。我需要知道scanner是否有两个next值: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

我想从CSV文件还原一个对象。我需要知道scanner是否有两个next值: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();
}

提前感谢您直接回答我认为您在问的问题:您可以检查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())
之前进行检查

正如评论中提到的满是鳗鱼的气垫船所建议的那样,最好采取另一种方法来解决这个问题。更好的是,由于这是一个CSV文件,您可以通过使用诸如或之类的库来省去很多麻烦。

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

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

没有直接的方法,你需要手动操作!破解一:使用扫描仪只读取行,而不是行上的单个标记,然后使用
String#split(…)
拆分每行。您将知道数组中有多少项。最佳解决方案一:使用CSV解析器——使用最好的工具来完成作业。dbank,感谢您的回复。在我的csv中,前两个字段是固定的。这是主人的名字和宠物的名字。我不需要检查它们,因为我知道它们在那里。如果没有,那么我有例外来处理这种情况。dbank,感谢您的回复。在我的csv中,前两个字段是固定的。这是主人的名字和宠物的名字。我不需要检查它们,因为我知道它们在那里。如果不是,那么我就有例外情况来处理该场景。我需要检查csv中剩下的内容是否是2的产品while循环使用了一个带有2个参数的构造函数。@user3738926我不确定我是否理解您现在提出的问题。你能详细说明你所说的“我需要检查csv中剩下的东西是否是2的产品”是什么意思吗?