0

我正在开发一个程序来读取二进制文件并将其更新为 txt 文件,它正在工作,突然它开始抛出这个错误

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)

这是导致错误的代码

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


    }

我真的坚持这个,所以任何帮助都会很棒

4

2 回答 2

2

在对 Scanner 对象调用 next() 之前,您应该调用 hasNext() 来检查是否实际上有更多数据要读取。

于 2013-04-11T15:43:32.050 回答
0

此代码部分容易出错:

else if (iSBN.compareTo(transISBN)==0)
{
    int change = trans.nextInt();
    amount += change;
    transISBN = trans.next();
}

你控制trans.hasNext()在 中while loop,但你没有在它的顶部transISBN = trans.next();放一个,我猜问题会得到解决。if(trans.hasNext())

于 2013-04-11T15:49:53.950 回答