1

我无法找到错误的根源。我所做的就是从文件中读取文本

public static void main(String[] args) throws Exception {
    int T;

    Scanner sc = new Scanner(new FileInputStream("problem3.txt"));

    T = sc.nextInt(); // first int in file, so T should be 2
}

并且错误消息显示 InputMismatchException:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at round1.Problem3.main(Problem3.java:11)

question3.txt的内容如下(3行,无空格):

2
36
127

我搜索了其他解决 InputMismatchException 的问题,但大多数都有“错误格式”的错误(试图将整数读取为字符串,反之亦然)。但就我而言,它应该没有问题,因为文件内容都是整数。

我还认为错误可能与'换行符(\ n)'有关。所以试过

T = sc.nextInt(); // error
sc.nextLine();

反之亦然

sc.nextLine();
T = sc.nextInt(); // error

两者仍然在同一行上给出相同的错误。

似乎是一个简单的问题,但我就是找不到。提前致谢。


问题已解决:我将编码更改为 Cp1252,它读取的是 2。谢谢大家

4

3 回答 3

0

这是一个编码问题。尝试使用 UTF-8 或 ANSI,您的代码应该可以正常运行,没有任何问题。

于 2015-10-24T21:49:22.250 回答
0

尝试给出正确的文件路径。我能够获取文件中的所有值

public static void main(String[] args) {
    // TODO Auto-generated method stub


    Scanner sc;
    try {
        sc = new Scanner(new FileInputStream("/Users/Zero/Desktop/problem3.txt"));


         int    T = sc.nextInt(); // first int in file, so T should be 2
         System.out.println(T);

        T = sc.nextInt();
         System.out.println(T);

         T = sc.nextInt();
         System.out.println(T);     
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

}

你能检查一下控制台上打印的内容吗

     StringBuffer a = new StringBuffer();
        while(sc.hasNext())
        {
        a.append(sc.nextLine());    
        }
         System.out.println(a.toString());
于 2015-10-24T21:34:23.003 回答
-1

试试看FileIO,看你想读什么,可能会容易很多

于 2015-10-24T21:33:58.780 回答