java - 没有这样的元素异常扫描器

标签 java nosuchelementexception

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/

相关文章:

java.lang.NoSuchMethodError : main error in simple java program

java - 如何安排测试和存储测试报告?

java - 在 webelement 上获取 NoSuchElementException (找到相同的 webelement,但有时我得到异常)

java - 线程 "main"java.util.NoSuchElementException 中的异常 - 无 close()

java - 使用 Scanner 一次读取一个文件夹中的所有文件会给出 NoSuchElementException

Java:坚持制作暂停功能

Java泛型-clearList实现

java - 通过连接池将 JMS 消息发送到 JBoss AS 中的远程队列

hadoop - 第一个使用 map 和 reducer 的 Hadoop 程序

java - 读取文件时出现无此类元素异常