如何修复扫描程序错误读取文件时出现的InputMismatchException错误?

时间:2015-04-16 01:10:23

标签: java file-io

我试图简单地读取文件中的第一个内容并设置一个变量来保存该值。该文件的第一行是10(见下文),我正在使用.nextInt()尝试读取该值但我收到此错误消息:

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 project5.Project5.readPlayers(Project5.java:39)
at project5.Project5.main(Project5.java:19)

以下是相关代码:

private static Player[] readPlayers( String fileName ) {
    String name = "", catchPhrase = "";
    int age = 0, count = 0;

    //set up to read the file
    Scanner inStream = new Scanner(fileName);

    //read the first line
    int numPlayers = inStream.nextInt();
    inStream.nextLine();

    //create arrays, one to hold all the possible players and one to hold if they are old enough
    Player[] allPlayers = new Player[numPlayers];
    boolean[] oldEnough = new boolean[numPlayers];

这是文件:

10
Rincewind 28 Luggage! 
MoistVonLipwig 30 Postal!
CaptainCarrotIronfoundersson 20 I am a 6'6 dwarf
GrannyWeatherwax 88 I ate'nt dead!
Eskarina 22 8th! 
Tiffany 19 Cheese! 
Vetinari 52 Si non confectus, non reficiat 
Igor 180 What goeth around, cometh around... or thtopth 
NobbyNobbs 17 tis a lie sir, i never done it 
DaftWullie 45 Aye, Criverns! 

我要做的就是阅读10并使用我的代码转到下一行。

1 个答案:

答案 0 :(得分:2)

这是因为你将一个字符串(包含文件名)传递给Scanner,它按字面解释。因此,如果fileName = "test.txt",您的所有扫描程序都包含"test.txt"(而不是文件的内容)。因此,当您执行scanner.nextInt()时,它会抛出异常,因为没有找到下一个整数(您只能scanner.next()才能获得fileName。但是,您要做的是将文件处理程序(使用File)传入Scanner,然后将该文件的内容读入流中,然后您可以像操作一样对其进行操作。 #39;重新尝试。

您想要做的是:

try {
    File file = new File(fileName);
}
catch (FileNotFoundException e) {
    e.printStackTrace();
}
Scanner inStream = new Scanner(file);

这会将文件内容读入Scanner,以便您可以执行您期望的操作。 (注意:File来自java.io.File