I’m making a class to read an object from file, that’s earlier saved to file(.txt format) but I receive the following error when trying to load the file:
java.util.NoSuchElementException
The method is made in such way so the user should be able to enter the name of the file. Even though it has been tried to debug abit and also just refer to the file itself with the name already given (not taking input). This is how the method looks:
public void load( String filename ) throws FileNotFoundException
{
final String FIELD_STOP = ":";
String loadFile;
loadFile = filename +".txt";
FileReader ansfil = new FileReader( loadFile );
Scanner fileIn = new Scanner( ansfil );
fileIn.useLocale( new Locale( "en" ) );
System.out.println(loadFile);
fileIn.useDelimiter( FIELD_STOP );
int size;
try
{
while( fileIn.hasNext() )
{
size = fileIn.nextInt();
archive = new CDarkivImplemented( size );
CD readIn = new CDImplemented();
for( int i = 0; i < size ; i++ )
{
readIn = new CDImplemented();
readIn.title = fileIn.next();
readIn.artist = fileIn.next();
readIn.genre = CD.interpretGenre( fileIn.next() );
readIn.publisher = fileIn.next();
readIn.year = fileIn.nextInt();
readIn.ID = fileIn.nextInt();
archive.addCD(readIn);
}
}
}
catch(Exception e)
{
System.out.println( "Wrong! : " + e );
System.exit(1);
}
fileIn.close();
}
What is that while loop for? As i infer from your comment about the file format you probably do not need this, and it might be causing the error due to it looping one more time after the last element has been read.