简体   繁体   中英

Exception in thread “main” java.util.NoSuchElementException

i have a file that consist like this

/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

and here is my StringTokenizer code:

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();
        }

i actually don't have any idea what is the problem as well as i researched every reason why nosuchelementexception would happened but i am not doing all those reasons why it won't work. any suggestions would be open thank you so much :)

    while(read.hasNext()){

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

From the above, Scanner read does not have any tokenizer, hence, read.hasNext() throws NoSuchElementEXception read.hasNextLine() should work fine

Exception java.util.NoSuchElementException This exception is thrown to indicate that there are no more elements in an 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);
    }

In your while loop you have condition for checking more elements using hasMoreElements() . But inside while loop you have for loop which calls nextElement() multiple times. If there is no elements in tokenizer then nextElement() will throw java.util.NoSuchElementException .

Solution :Add some condition in for loop for checking elements in tokenizer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM