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()、正则表达式、检查字母等。
然而,错误不是意志。
抱歉,再问一次。
如何提供帮助将不胜感激。
最佳答案
一个问题可能与混合使用 nextLine
和 next
/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();
...
}
...
}
关于java - 我如何嵌套迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30147033/