线程“main”java.util.NoSuchElementException中的异常

时间:2016-09-09 16:00:06

标签: java file oop stringtokenizer

我有一个像这样的文件

/1/a/a/a/Female/Single/a/a/January/1/1920/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a

这是我的StringTokenizer代码:

public void retrieveRecords(){
        String holdStr="";
        try {
            fileRead=new FileReader(fileNew);
            read=new Scanner(fileRead);

            while(read.hasNext()){
                holdStr+=read.nextLine()+"\n";
            }
            read.close();

            StringTokenizer strToken=new StringTokenizer(holdStr, "/");

            while(strToken.hasMoreElements()){
                rows=new Vector();
                for(int i=0; i<column.length; i++){
                    rows.add(strToken.nextElement());
                }
                ViewTablePanel.tblModel.addRow(rows);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

我实际上不知道问题是什么,我研究了nosuchelementexception发生的每一个原因,但我没有做所有这些因为它不起作用的原因。任何建议都会开放,非常感谢你:))

2 个答案:

答案 0 :(得分:1)

    while(read.hasNext()){

          holdStr+=read.nextLine()+"\n";
     }

从上面看,Scanner读取没有任何tokenizer,因此,read.hasNext()抛出NoSuchElementEXception read.hasNextLine()应该可以正常工作

答案 1 :(得分:1)

异常java.util.NoSuchElementException抛出此异常表示tokenizer中没有其他元素。

    while(strToken.hasMoreElements()){
        rows=new Vector();
        for(int i=0; i<column.length; i++){
            rows.add(strToken.nextElement()); //Exception will throw on this line
        }
        ViewTablePanel.tblModel.addRow(rows);
    }

while循环中,您有条件使用hasMoreElements()检查更多元素。但是在while循环中你有for循环,多次调用nextElement()。如果tokenizer中没有元素,则nextElement()将抛出java.util.NoSuchElementException

解决方案:在for循环中添加一些条件以检查tokenizer中的元素。