0

I seem to be having some trouble getting my code to run properly here. What this is supposed to do is it is supposed to read from a text file and find the name, quantity, and price of an item on each line then format the results. The tricky bit here is that the items have names that consist of two words, so these strings have to be differentiated from the quantity integer and price double. While I was able to get this working, the problem that I am having is with a singe space that is at the very end of the text file, right after the last item's price. This is giving me a java.util.NoSuchElement Exception: null, and I cannot seem to move past it. Can someone help me to work out a solution? The error is on 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

問題は、内側の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();
}
于 2013-09-25T07:12:35.660 に答える