Reputation: 13
i am working on a program to read a binary file and update it form a txt file, it was working the all of a sudden it started throwing this error
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at StockManage.updateInv(StockManage.java:134)
at StockManage.main(StockManage.java:173)
heres the code thats causes the error
try
{
Scanner trans = new Scanner(new File(file));
RandomAccessFile inv = new RandomAccessFile (file2,"rws");
String tempName = "Temp" + (int)(Math.random()*1000000) + ".dat";
RandomAccessFile newInv = new RandomAccessFile (tempName , "rws");
File newFile = new File(tempName);
String transISBN = trans.next();
String author = inv.readUTF();
String title = inv.readUTF();
String iSBN = inv.readUTF();
int amount = inv.readInt();
while (inv.getFilePointer()<=inv.length())
{
boolean empty = true;
while (empty&&trans.hasNext())
{
if (iSBN.compareTo(transISBN)<0)
{
empty = false;
break;
}
else if (iSBN.compareTo(transISBN)==0)
{
int change = trans.nextInt();
amount += change;
transISBN = trans.next();
}
}
newInv.writeUTF(author);
newInv.writeUTF(title);
newInv.writeUTF(iSBN);
newInv.writeInt(amount);
author = inv.readUTF();
title = inv.readUTF();
iSBN = inv.readUTF();
amount = inv.readInt();
}
im really stuck in this one so any help would be great
Upvotes: 0
Views: 101
Reputation: 5447
This code part is error-prone:
else if (iSBN.compareTo(transISBN)==0)
{
int change = trans.nextInt();
amount += change;
transISBN = trans.next();
}
You control trans.hasNext()
in the while loop
, but you don't before transISBN = trans.next();
put an if(trans.hasNext())
at the top of it and problem will be solved, I guess.
Upvotes: 0
Reputation: 19225
Before calling next() on a Scanner object you should call hasNext() to check if there is actually more data to read.
Upvotes: 2