NoSuchElement异常错误

时间:2013-09-25 06:31:21

标签: java

我似乎在让代码在这里正常运行时遇到了一些麻烦。这应该做的是它应该从文本文件中读取并找到每行上项目的名称,数量和价格,然后格式化结果。这里棘手的一点是项目的名称由两个单词组成,因此这些字符串必须与数量整数和价格双倍区分开来。虽然我能够使这个工作,但我遇到的问题是在文本文件的最末端有一个单独的空间,就在最后一个项目的价格之后。这给了我一个java.util.NoSuchElement Exception: null,我似乎无法超越它。有人可以帮我找出解决方案吗?错误发生在thename = thename + " " + in.next();

while (in.hasNextLine())
        {
            String thename = "";

            while (!in.hasNextInt())
            {
                thename = thename + " " + in.next();
                thename = thename.trim(); 
            }
            name = thename;
            quantity = in.nextInt();
            price = in.nextDouble();

        }

2 个答案:

答案 0 :(得分:0)

您需要确保Name quantity price字符串格式正确。字符串中可能没有足够的令牌。要检查名称是否有足够的令牌:

 while (!in.hasNextInt())
        {
            thename = thename + " ";
            if (!in.hasNext())
                throw new SomeKindOfError();
            thename += in.next();
            thename = thename.trim(); 
        }

您不必抛出错误,但您应该根据自己的需要使用某种代码来正确处理此问题。

答案 1 :(得分:0)

问题出在内部while循环的逻辑中:

while (!in.hasNextInt()) {
    thename = thename + " " + in.next();
}

在英语中,这表示“虽然一个int可用,但请阅读下一个标记”。该测试无助于检查下一步操作是否成功。

您没有检查是否有下一个令牌可供阅读。

考虑将您的测试更改为使操作安全的测试:

while (in.hasNext()) {
    thename = thename + " " + in.next();
    thename = thename.trim(); 
    name = thename;
    quantity = in.nextInt();
    price = in.nextDouble();
}
相关问题