2013-10-21 114 views
0
public class Test 
{ 
    public static void main(String[] args) throws FileNotFoundException 
    { 
     Scanner input = new Scanner("text.txt"); 
     int x = input.nextInt();   
    } 
} 

的text.txt感:为什么会抛出InputMismatchException?

8 
8 
6 
7 

此代码抛出一个InputMismatch异常。为什么?

回答

3

这是因为"text.txt"不是一个数字。请尝试:

Scanner input = new Scanner(new File("text.txt")); 
+0

该死的我觉得自己像个白痴。谢谢! – Qwertywasd

+0

我认为你的意思是“文件”。 :) – Zong

+0

不:)我的意思是数字。我应该说:*'text.txt'是一个不包含数字的字符串。* –

1

构造函数Scanner(String)接受从中读取的字符串,而不是文件名。

因此,nextInt()正试图从您传递给它的字符串中读取int,即。 "text.txt"

而是使用接受File源的构造函数,Scanner(File)

0

问题是由于重载。您正在调用新的扫描仪(字符串)而不是新的扫描仪(文件)。如果你尝试scanner.next()你会看到它返回“text.txt”

相关问题