Scanner s = new Scanner(new File("src/mail_list"));
while (s.hasNextLine()){
String line1 = s.nextLine();
if (line1.startsWith("Users")){
line1 = s.nextLine();
while (!(line1 = s.nextLine()).isEmpty()) {
String arr[] = line1.split(" ", 4);
users.add(new User(arr[0],arr[1],arr[2],arr[3]));
}
}
if (line1.startsWith("Lists")){
line1 = s.nextLine();
while (!(line1 = s.nextLine()).isEmpty()) { //exception here
String arr1[] = line1.split(" ", 2);
ArrayList<String> tmp = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(arr1[1]);
while (st.hasMoreTokens()) {
tmp.add(st.nextToken());
}
list.add(new List((arr1[0]), tmp));
}
}
}
/*-testfile-start*/
Keyword: Users
username1 Name1 Surname1 email1
username2 Name2 Surname2 email2
Keyword: Lists
list_name username1 username2 ...
/*-testfile-end*/
我正在使用上面的代码来对上面的测试文件模式进行排序。基本上这意味着如果我遇到关键字“用户”,我必须添加关于用户的所述信息。
我在代码中标记了异常发生的地方。关于如何应对它的任何想法?
最佳答案
您正在调用 nextLine()
两次,但只检查一次 hasNextLine()
。
String line1 = s.nextLine();
if (line1.startsWith("Users")){
line1 = s.nextLine();
这意味着您在不知道是否有下一行的情况下获取下一行,如果没有则抛出异常。
关于java - 没有这样的元素异常扫描器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29704125/