用于解析输入的代码抛出InputMismatchException

时间:2011-11-19 21:43:09

标签: java io

while(inputbook.hasNext()){
    id = inputbook.nextInt();
    name = inputbook.next();
    year = inputbook.nextInt();
    price = inputbook.nextDouble();
    Book b = new Book(id,name,year,price);
    hmbook.put(id,b);
    Book b2 = hmbook.get(id);
    System.out.println(b2);

    getCb3();
    cb3.addItem(name);
}

这是文本文件:

100 JAVA 2007 100.0
200 C++ 2005 65.9
300 Introduction 2008 120.0 

但我得到InputMismatch例外:

Exception in thread "AWT-EventQueue-0" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextDouble(Unknown Source)
    at FirstFrame.loadFiles(FirstFrame.java:143)
    at FirstFrame.<init>(FirstFrame.java:712)
    at FirstFrame$7.run(FirstFrame.java:699)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

这是例外。为什么会这样?

1 个答案:

答案 0 :(得分:2)

可能是您的语言环境需要使用逗号作为小数分隔符的双精度数。你可以试试

Scanner inputbook = new Scanner(new File("book.txt"));
inputbook.useLocale(Locale.US);

并查看是否有任何改变。我还要添加

while(inputbook.hasNext()){
    id = inputbook.nextInt();
    System.out.println("id=" + id);
    name = inputbook.next();
    System.out.println("name=" + name);
    year = inputbook.nextInt();
    System.out.println("year=" + year);
    price = inputbook.nextDouble();
    System.out.println("price=" + price);

这样你就会知道最后成功读取的变量是什么,并且更容易确定出现了什么问题。