我如何嵌套Iterator?

时间:2015-05-10 02:19:14

标签: java iterator iteration

while (inFile.hasNextLine()) {
    SortedArrayList<Fruit> fruitList = new SortedArrayList<Fruit>();
    String marketName = inFile.next();
    while (inFile.hasNexLine()) {
        String line = inFile.nextLine();
        if(line.isEmpty())
            break;
        else {
                Sting fruitName = inFile.next();
                int price = inFile.nextInt();
                int stock = inFile.nextInt();
                fruit = new Fruit(fruitName, price, stock);
                fruitList.insert(fruit);
        }        
    }
    market = new Market(marketName, fruitList);
    marketList.insert(market);
}

我想要阅读文本文件 文本文件的内容如下:

A_market  
apple 1000 11  
orange 2000 6   
grape 1600 17

B_market  
apple 900 20   
orange 2100 12  

...

每个市场都无法提前知道每种水果的数量 每个市场将用空行分隔 如何识别文本文件中的空白行?

我希望在嵌套迭代器的基础上留空 我尝试isEmpty(),正则表达式,检查字母表等。
但是,错误不是意志。

再次抱歉问题。
如何提供帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

一个问题可能与混合nextLinenext / nextInt有关。请参阅Skipping nextLine() after use next(), nextInt() or other nextFoo() methods

通常混合这些是一个坏主意。选择其中一个。

您的部分内容也会被彻底删除:

// this line is being skipped
// when it's not empty
String line = inFile.nextLine();
if(line.isEmpty())
    break;
else {
    Sting fruitName = inFile.next();
    int price = inFile.nextInt();
    int stock = inFile.nextInt();
    ...
}

我建议每次想要从一行获取每个水果的信息时使用第二个Scanner

while (inFile.hasNextLine()) {
    String marketName = inFile.nextLine();

    while (inFile.hasNextLine()) {
        String line = inFile.nextLine();
        if (line.isEmpty()) {
            break;
        }

        // create a new Scanner just
        // for this line so it doesn't
        // mess up the calls to nextLine
        Scanner lineIn = new Scanner(line);

        Sting fruitName = lineIn.next();
        int price = lineIn.nextInt();
        int stock = lineIn.nextInt();
        ...
    }

    ...
}

答案 1 :(得分:0)

Java代码

 while (inFile.hasNextLine()) {
        String marketName = inFile.next();
        while (inFile.hasNexLine()) {
            String line = inFile.nextLine();
            if(line.length()==0)     //blank line
                break;
            else {
                    Sting fruitName = inFile.next();
                    int price = inFile.nextInt();
                    int stock = inFile.nextInt();
                    fruit = new Fruit(fruitName, stock, price);
                    fruitList.insert(fruit);
            }        
        }
        market = new Market(marketName, fruitList);
        marketList.insert(market);
    }