gpt4 book ai didi

Java 扫描器与 2 hasNext()

转载 作者:行者123 更新时间:2023-12-02 04:53:47 32 4
gpt4 key购买 nike

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

提前致谢

最佳答案

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

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

关于Java 扫描器与 2 hasNext(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28977021/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com