首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >带有2 hasNext()的Java扫描仪

带有2 hasNext()的Java扫描仪
EN

Stack Overflow用户
提问于 2015-03-11 01:21:53
回答 2查看 1.1K关注 0票数 0

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

问题是,我的访问构造函数接受两个参数,我需要确保至少还有两个在我的csv文件中。

以下是相关代码:

代码语言:javascript
运行
复制
    /**
 * 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();
}

提前感谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-03-11 01:40:25

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

代码语言:javascript
运行
复制
String pattern = ".*,.*";
while (scan.hasNext(pattern)) {
  ...
}
票数 1
EN

Stack Overflow用户

发布于 2015-03-11 01:31:22

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

代码语言:javascript
运行
复制
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在评论中所建议的那样。更好的是,因为这是一个CSV文件,所以使用公域CSV露天矿这样的库可以省去很多麻烦。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28977021

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档