从文件中读取NoSuchElementException

时间:2015-04-25 18:16:31

标签: java file file-io

所以我试图从文本文件中的每一行读取前4个变量。

但它抓住了NoSuchElementException

public static void readRecords()
    {
        System.out.printf("%s%s%s%s" , "Team Id", "TeamNAme","CoachFirst", "CoachLast");
        try
        {
            while (input.hasNext())
            {
                System.out.printf("%s%s%s%s",input.nextInt(),input.next(),input.next(),input.next());

            }

        }
        catch (NoSuchElementException statException)
        {
            System.err.println("File improperly formed.");
        }
        catch (IllegalStateException stateException)
        {
            System.err.println("ERROR READING FROM FILE");
        }
    }

有关为何发生这种情况的任何想法?

这是文件元素:

TeamNumber,Team Name,Coach First,Coach Last,Mentor First,Mentor Last,Team Fin Sponsor,Schools or Sponsoring Organization,TmMem1First,TmMem1Last,TmMem2First,TmMem2Last,TmMem3First,TmMem3Last,TmMem4First,TmMem4Last,TmMem5First,TmMem5Last,TmMem6First,TmMem6Last,TmMem7First,TmMem7Last,TmMem8First,TmMem8Last
6842,Reagan Ray-Guns,Judy,Mallon,Aziz,Valdez,Texas Workforce Commission,REAGAN H S,Steven,Cepeda,Alan,Yue,Tim,Callaway,Damon,Bertucci,Samuel,de Olvieira,Samuel,Day,,,,
6888,Islanders,Judy,Maldonado,Brady,Trevino,Three Rivers Robotics,THREE RIVERS MIDDLE,Shireen,Cowdrey,Dee,Roundtree,Steven,Callaway,Francisco,Bermea,,,,,,,,
7004,GREENHILL Tops,Kanat,LaBass,Harvey,Pflueger,GREENHILL Boosters,GREENHILL SCHOOL,Harvey,Pflueger,Sandra,Day,Denny,Rodriguez,shirley,Couvillon,Carly,Szarka,,,,,,

3 个答案:

答案 0 :(得分:1)

您只检查了下一个元素(hasNext())方法,但随后调用了nextInt()四次。

每次调用nextInt()时,都应该检查是否有更多的整数。也请改用hasNextInt()

答案 1 :(得分:0)

您输入的第一行实际上并不是以int开头,因此在其上调用nextInt()将失败。据推测,您希望在阅读后面的实际数据之前先跳过该行。

答案 2 :(得分:0)

好吧,您正在阅读4个变量,但示例文本文件中的每一行都有4个以上的条目(假设您使用,作为扫描仪分隔符)。这意味着您需要调用Scanner#nextLine()来跳过该行的其余输入。

public static void readRecords()
{
    System.out.printf("%s%s%s%s" , "Team Id", "TeamNAme","CoachFirst", "CoachLast");
    try
    {
        while (input.hasNext())
        {
            System.out.printf("%s%s%s%s",input.nextInt(),input.next(),input.next(),input.next());
            input.nextLine();  // skip remainder of line
        }

    }
    catch (NoSuchElementException statException)
    {
        System.err.println("File improperly formed.");
    }
    catch (IllegalStateException stateException)
    {
        System.err.println("ERROR READING FROM FILE");
    }
}