我正在开发一个程序,该程序打开一个数据文件并使用 while 循环逐行读取该文件,以将数据存储在二叉搜索树中。我唯一的问题是我不确定如何处理循环条件,因为文件的最后一行没有换行符。我通常使用 hasNextLine() 和扫描仪来读取文件,但这会在我的程序中引发错误,并且我不能使用 hasNext() 因为我需要抓取整行,而不仅仅是其中的一部分。解决这个问题的最佳方法是什么?
public static BinaryTree getInventory(BinaryTree tree, Scanner input) {
String line, title = "";
int available = -1, rented = -1, comma = 0;
boolean quote = true;
// While not the end of file
while (input.hasNextLine()) {
line = input.nextLine();
for (int i = 1; i < line.length(); i++) {
if (line.charAt(i) == '"') {
title = line.substring(1, i);
comma = i + 1;
quote = false;
i++;
}
else if (line.charAt(i) == ',' && !quote) {
available = Integer.parseInt(line.substring(comma + 1, i - 1));
comma = i;
i++;
}
else if (i + 1 == line.length()) {
rented = Integer.parseInt(line.substring(comma + 1, i));
}
}
tree.insert(new Node(title,available,rented));
}
return tree;
}
最佳答案
您可以通过捕获 NoSuchElementException
来避免使用 hasNext()
。另外,考虑到文件的结构(似乎是 "title",XX,YY
),您可以避免使用这样的代码循环遍历行字符
try {
while (true) {
String line = input.nextLine();
int rdquo = line.indexOf('"', 1);
String title = line.substring(1, rdquo);
String[] avail = line.substring(rdquo+2).split(",");
tree.insert(new Node(title, Integer.parseInt(avail[0]) , Integer.parseInt(avail[1]));
}
} catch (NoSuchElementException reachedEndOfFile) { }
关于Java:当并非所有行都有新行时从文件中读取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43328604/