没有这种元素异常扫描器

时间:2015-04-17 16:00:31

标签: 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*/

我使用上面的代码来从上面的testfile模式中对事物进行排序。基本上它意味着如果我遇到关键字&#34;用户&#34;我必须添加关于用户的所述信息。

我在代码中标记了异常上升的地方。关于如何应对它的任何想法?

5 个答案:

答案 0 :(得分:1)

您正在拨打nextLine()两次,但只检查hasNextLine()一次。

String line1 = s.nextLine();
    if (line1.startsWith("Users")){
        line1 = s.nextLine();

意味着你在不知道是否存在下一行的情况下获取下一行,如果没有,则抛出异常。

答案 1 :(得分:1)

我找到了一个愚蠢的解决方案。我刚刚在最后一行之后添加了一个'虚拟'字符2行。它的工作原理。它不是一个完美的解决方案,但由于测试文件不是任何人都能看到的,我现在就把它拿走...... 感谢所有与我一起集思广益45分钟的人。

答案 2 :(得分:0)

Do!(line1 = s.nextLine())!= null,不为空,因为它无法读取空行。

答案 3 :(得分:0)

来自Scanner#nextLine

  

<强>抛出:
   NoSuchElementException - 如果没有找到任何行。

你有这个代码:

while (s.hasNextLine()) {
    //checked if there's line to read
    String line1 = s.nextLine();
    if (line1.startsWith("Users")) {
        //not checked if there's line to read
        line1 = s.nextLine();
        //not checked here either
        while (!(line1 = s.nextLine()).isEmpty()) {
            String arr[] = line1.split(" ", 4);
            users.add(new User(arr[0],arr[1],arr[2],arr[3]));
        }
    }
    //similar in code below...
}

确保在使用Scanner#nextLine之前验证要读取的行。相应地处理例外情况。

答案 4 :(得分:0)

enter image description here

如您所见,此方法在未找到任何行时抛出NoSuchElementException。

if (line1.startsWith("Lists")){
        line1 = s.nextLine(); // <=============== ?
        while (!(line1 = s.nextLine()).isEmpty()) { //exception here

您如何知道在那里和评论栏中有更多行?

相关问题