0

我在nextLine()阅读文本文件时遇到问题。之前,我尝试使用这种文本文件.next(),它工作正常。

2
3333
CookingRange
50 450.00 850.00
4444
CircularSaw
150 45.00 125.00

现在我想从nextLine()用于读取行的文件中读取输入,即使它在字符串之间有空格。

2
3333
Cooking Range
50 450.00 850.00
4444
Circular Saw
150 45.00 125.00

我有这种错误

http://i.stack.imgur.com/CHfGp.png

所以基本上我的代码看起来像这样

public class console {
    public static void main(String[] args) throws IOException {
        Scanner inFile = new Scanner(new FileReader("items.in"));

        //products

        int itemCount = inFile.nextInt();
        Vector<item> pList = new Vector<item>();

        double totalProfitForItem = 0.0;
        double totalSellingvalueForItem =  0.0;
        double totalAmount = 0.0;
        int totalStock = 0;

        String itemID;
        String itemName;
        int pcsInStore;
        double manufPrice;
        double sellingPrice;
        int j;

        for (int i = 0; i < itemCount; i++) {

            itemID = inFile.nextLine();
            itemName = inFile.nextLine();
            pcsInStore = inFile.nextInt();
            manufPrice = inFile.nextDouble();
            sellingPrice = inFile.nextDouble();

            item s = new item(itemID, itemName, pcsInStore, manufPrice, sellingPrice, totalSellingvalueForItem, totalProfitForItem);
            pList.addElement(s);

            totalAmount += totalSellingvalueForItem;
            totalStock += pcsInStore;
        }


        for( j = 0; j < pList.size(); j++) {
            System.out.printf("%5s %5s  %5.2f %.2f \n", pList.elementAt(j).getItemID(), pList.elementAt(j).getItemName(), pList.elementAt(j).totsell(), pList.elementAt(j).totprof());
            totalSellingvalueForItem = pList.elementAt(j).totsell();
            totalAmount += totalSellingvalueForItem ;
        }

        System.out.println("\n");
        System.out.println("Total Amount of Inventory: " + totalAmount +"0");
        System.out.println("Number of Items in the Store: " + totalStock);    
    }    
}
4

2 回答 2

1

那是因为nextDouble/nextInt读取/的值,并不会读取你在读取数字后按下的 ,所以它会在.doubleint'\n'nextLine

对此的一种解决方案是在“真实”之前添加另一个nextLine“吞下”,'\n'以便您可以读取第二个中的实际值nextLine

关于InputMismatchException,这:

由 Scanner 抛出以指示检索到的令牌与预期类型的​​模式不匹配

可能是'\n'被读入的结果,nextInt也可能是nextDouble因为上面提到的。

于 2013-10-20T08:26:29.807 回答
1

nextDouble并且nextInt仅分别读取 double 或 int 值,但会忽略每行末尾不可见的“\n”。因此,当您继续阅读下一项时,它会尝试将 "\n" 作为 int 或 double 读取,从而导致InputMismatchException. 一个解决方案是.nextLine()在您读取一个数字并丢弃该值(不要将其存储在变量中)之后执行,以便读取“\n”并在将来忽略它。

于 2013-10-20T08:30:46.950 回答