0

我似乎很难让我的代码在这里正常运行。这应该做的是它应该从一个文本文件中读取并在每一行上找到一个项目的名称、数量和价格,然后格式化结果。这里棘手的一点是项目的名称由两个单词组成,因此必须将这些字符串与数量整数和价格加倍区分开来。虽然我能够做到这一点,但我遇到的问题是文本文件末尾的单个空格,就在最后一个项目的价格之后。这给了我一个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();

        }
4

2 回答 2

0

The problem is in the logic of your inner while loop:

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

In English, this says "while there's not an int available, read the next token". The test does nothing to help check if the next action will succeed.

You aren't checking if there is a next token there to read.

Consider changing your test to one that makes the action safe:

while (in.hasNext()) {
    thename = thename + " " + in.next();
    thename = thename.trim(); 
    name = thename;
    quantity = in.nextInt();
    price = in.nextDouble();
}
于 2013-09-25T07:12:35.660 回答
0

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

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

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

于 2013-09-25T06:42:56.133 回答