Start New Discussion within our Software Development Community

Hi there, I wondered if some one would be able to put me through with this, as i am a newbie in Java. I have the following text file named dvdifo:

*Donnie Darko/sci-fi/Gyllenhall, Jake
Raiders of the Lost Ark/action/Ford, Harrison
2001/sci-fi/??
Caddy Shack/comedy/Murray, Bill
Star Wars/Sci-fi/Ford, Harrison
Lost in Translation/comedy/Murray, Bill
Patriot Games/action/Ford, Harrison
*

I want to create an instance of DVDInfo for each line of data I read in from the dvdinfo.txt file, and then put them in an arraylist. My DVDInfo class that i wrote is as follows:

import java.util.*;
class DVDInfo 
{
  String title;
  String genre;
  String leadActor;

 DVDInfo(String t, String g, String a)
  {
   title = t; genre = g; leadActor = a; 
  }

 public String toString() 
  {
   return title + "" + genre + "" + leadActor + "\n";
  }


 public static void main(String [] args)
  {

      Scanner search = new Scanner("dvdinfo.txt").useDelimiter("/");

      String Title = "", Genre = "", Lead = "", line;

         ArrayList<DVDInfo> dvdlist = new ArrayList<DVDInfo>();


         try

            {

                while (search.hasNextLine())

                 {
                    Title = search.next();

                    Genre = search.next();

                    Lead = search.next();

                    search.nextLine();

                    DVDInfo DVD = new DVDInfo(Title, Genre, Lead);

                    dvdlist.add(DVD);


                  }
           }

         finally

            {
              search.close();
            }


           for( DVDInfo d : dvdlist)

             {
               System.out.println(d.toString());
             }      
}

}

When I run the above programme, it gave me an error: Exception in thread "main" java.util.NoSuchElementException. I have been looking for what i am doing wrong, and i can't figure this out.I will be very grateful if someone could please point me to the right direction. Many thanks.

Which line is generating the Exception? The third next()?

Scanner looks like a good idea for beginners to use, but in reality it's full of little traps that cause all kinds of problems (eg: if you have delimiter of "/" then a new line is no longer a delimiter [Hint!]), and collapses in chaos if there's anything wrong with theinput data.

For data like yours you will be on much safer ground, with less code and fewer possible errors, if you:
use a BufferedReader to read the file one line at a time
use String's split("/") method to split each line into an array of substrings
use the array elements to create your dvd object.

This article has been dead for over six months. Start a new discussion instead.