2016-09-25 53 views
-1
package baker; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 


public class FileReader { 

    public static void main(String[] args) throws FileNotFoundException { 
     String name; 
     double height; 
     double inches; 
     double idealWeight; 

     Scanner fileReader; 
     fileReader = new Scanner(new FileInputStream("Data/patients.txt")); 
     while (fileReader.hasNext()) { 

      name = fileReader.next(); 
      System.out.println("Name: "); 
      height = fileReader.nextInt(); 
      inches = fileReader.nextInt(); 

      fileReader.nextLine(); 
      idealWeight = 110 + (height - 5) * 5 + inches * 5; 
      System.out.println("Ideal Weight: " + idealWeight); 


    } 
    } 
} 

此代码引发以下错误:InputMismatchException尝试使用Scanner时,我错过了什么?

Exception in thread "main" java.util.InputMismatchException 
    at java.util.Scanner.throwFor(Scanner.java:864) 
    at java.util.Scanner.next(Scanner.java:1485) 
    at java.util.Scanner.nextInt(Scanner.java:2117) 
    at java.util.Scanner.nextInt(Scanner.java:2076) 
    at baker.FileReader.main(FileReader.java:22) 
C:\Users\SFU\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1 
BUILD FAILED (total time: 0 seconds) 

错误点的最后一行到第22行,这是以下行:

height = fileReader.nextInt(); 

至于我可以告诉大家,输入不匹配错误没有理由。有什么建议么?我已经在下面发布了问题文件(patients.txt)。

Tom Atto 
6 
3 
Eaton Wright 
5 
5 
Cary Oki 
5 
11 
+0

它与FileInputStream没有任何关系。它与*输入数据有关。* – EJP

回答

1

的原因是因为你的name分配。你做到以下几点:

name = fileReader.next(); 

事实是next返回下令牌默认由空格分隔。每Javadocs

public String next()

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

所以,你现在可以看到的是,第一个和最后的名字可能会出现问题。举例来说,如果你有这一个文件:

John Smith 

你做的事:

scanner.next(); 

你将只能得到John,因为它是一个完整标记,并在空间分隔。这意味着,当你再扫描整数:

scanner.nextInt(); 

扫描仪会遇到Smith(串),并抛出一个InputMismatchException。使用方法:

name = fileReader.nextLine(); 

改为接收整行。这将产生John Smith。阅读更多关于here

相关问题