代码编译,但我得到NoSuchElementException错误

时间:2014-09-25 05:24:19

标签: java exception exception-handling stringtokenizer

这个程序假设一个人的名字,性别和人数都有这个名字,并且在一个字符串中有单独的名字,性别变成一个字符,以及名字变成int的人数。已经计算了具有该名称的人数我只需要将每个人分成正确的类别。 问题是代码编译但我收到NoSuchElementException错误。

文件如下所示:

约翰,男,416

萨拉,F,414

麦克,男,413

凯特,F,413

    ArrayList<OneName> oneName = new ArrayList<OneName>();
    while(sc.hasNextLine())
    {

    // read a line from the input file via sc into line
        line = sc.nextLine();
        String[] fields =line.split(",");


        StringTokenizer stk = new StringTokenizer(line);
        String name = stk.nextToken();
        char sex = stk.nextToken().charAt(0);
        int count = Integer.parseInt(stk.nextToken());


        OneName list = new OneName(name, sex, count);

        oneName.add(list);      


    }
   String personSex = oneName.get(0).getName();
    System.out.println(personSex);
    }

3 个答案:

答案 0 :(得分:0)

您必须将分隔符设置为逗号:

StringTokenizer stk = new StringTokenizer(line,",");

它会起作用。

如果您没有设置分隔符,它将设置为\r\n

答案 1 :(得分:0)

当您使用StringTokenizer作为

StringTokenizer stk = new StringTokenizer("John,M,416"); 

您的文字将由\t\n\r\f标记。因此stk.nextToken()将为您John,M,416,如果您再次致电stk.nextToken(),您将获得NoSuchElementException

例如:

StringTokenizer stk = new StringTokenizer("John,M,416");
System.out.println(stk.nextToken());
System.out.println(stk.nextToken());

Out put:

John,M,416
Exception in thread "main" java.util.NoSuchElementException...

因此您需要使用StringTokenizer,如下所示

StringTokenizer stk = new StringTokenizer("John,M,416",",");
while (stk.hasMoreElements()){
   System.out.println(stk.nextToken());
}

现在你出去了

John
M
416

代码中的错误在哪里?

 StringTokenizer stk = new StringTokenizer(line);
 String name = stk.nextToken(); // this line is ok
 char sex = stk.nextToken().charAt(0); // ohh this one cause the issue   

答案 2 :(得分:0)

你需要用StringTokenizer传递这两个参数。第一个是你的字符串&amp;第二个需要解析的regix。

 ArrayList<OneName> oneName = new ArrayList<OneName>();
        while(sc.hasNextLine())
    {

    // read a line from the input file via sc into line
        line = sc.nextLine();
        String[] fields =line.split(",");


        StringTokenizer stk = new StringTokenizer(line,",");
        String name = stk.nextToken();
        char sex = stk.nextToken().charAt(0);
        int count = Integer.parseInt(stk.nextToken());


        OneName list = new OneName(name, sex, count);

        oneName.add(list);      


    }
   String personSex = oneName.get(0).getName();
    System.out.println(personSex);
    }

希望有所帮助