[英]Scanner - Ignore new line at end of file
进入/忽略文件reg.txt中的最后一行时,我需要退出方面的帮助。 截至目前,当它到达最后一行时不显示任何错误。
public String load() {
list.removeAllElements();
try {
Scanner scanner = new Scanner(new File("reg.txt"));
while (scanner.hasNextLine()) {
String lastname = scanner.next();
String firstname = scanner.next();
String number = scanner.next();
list.add(new Entry(firstname, lastname, number));
}
msg = "The file reg.txt has been opened";
return msg;
} catch (NumberFormatException ne) {
msg = ("Can't find reg.txt");
return msg;
} catch (IOException ie) {
msg = ("Can't find reg.txt");
return msg;
}
}
reg.txt示例:
Allegrettho Albert 0111-27543
Brio Britta 0113-45771
Cresendo Crister 0111-27440
我应该如何编辑扫描仪的读数,以便忽略文件末尾的新行?
在循环结束时,执行
Scanner.nextLine();
一种干燥而肮脏的方法是在每一个scan.next()之前检查是否有下一行。
if(scanner.hasNextLine())
{
lastname = scanner.next();
}
或在字符串姓氏之后:
if(!lastname.isEmpty())
{
//continue here...
}
您可以为Entry参数添加一个验证,如果有空行,您将跳过它。
if(firstname != null || lastname != null || number != null) {
list.add(new Entry(firstname, lastname, number));
}
最简单的方法可能是将数据集合包含在if语句中,以检查scanner.next()是否不为空:
while (scanner.hasNextLine()) {
if(!scanner.next().equals("")&&!scanner.next()==null){
String lastname = scanner.next();
String firstname = scanner.next();
String number = scanner.next();
list.add(new Entry(firstname, lastname, number));
}
}
否则,我会看看您的hasNextLine方法,以了解当下一行为空时说“是的,我有下一行”的逻辑;)
与其使用next()
读取最后一个字段, nextLine()
使用nextLine()
。 这将使扫描仪前进到行尾,但不会在结果中返回行尾字符。
scanner.hasNextLine()
将为false
,因此循环不会再次开始。
while (scanner.hasNextLine()) {
String lastname = scanner.next();
String firstname = scanner.next();
String number = scanner.nextLine();
list.add(new Entry(firstname, lastname, number));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.