【问题标题】:Java NoSuchElementException using scanner.nextInt()Java NoSuchElementException 使用scanner.nextInt()
【发布时间】:2011-11-16 01:46:41
【问题描述】:

我正在尝试读入一个 pgm 文件(512x512 数组),当我读入一个更大的文件时,我收到错误:java.util.NoSuchElementException 读取元素 (3,97)。

我创建了一个小得多的文件来读取 (23x23),它可以正常读取。有大小限制吗?我检查了文件并确认该值有一个 int : 这似乎是它崩溃的那一行:

fileArray[row][col] = scan.nextInt();

这是文件:

import java.util.Scanner;
import java.io.*;

public class FileReader {
    public static void main(String[] args) throws IOException {

        String fileName = "lena.pgma";
        int width, height, maxValue;
        FileInputStream fileInputStream = null;

        fileInputStream = new FileInputStream(fileName);
        Scanner scan = new Scanner(fileInputStream);
        // Discard the magic number
        scan.nextLine();
        // Discard the comment line
        scan.nextLine();
        // Read pic width, height and max value
        width = scan.nextInt();
        System.out.println("Width: " + width);

        height = scan.nextInt();
        System.out.println("Heigth: " + height);
        maxValue = scan.nextInt();

        fileInputStream.close();

         // Now parse the file as binary data
         FileInputStream fin = new FileInputStream(fileName);
         DataInputStream dis = new DataInputStream(fin);

         // look for 4 lines (i.e.: the header) and discard them
         int numnewlines = 4;
         while (numnewlines > 0) {
             char c;
             do {
                 c = (char)(dis.readUnsignedByte());
             } while (c != '\n');
             numnewlines--;
         }

        // read the image data
         int[][] fileArray = new int[height][width];

         for (int row = 0; row < height; row++) {
             for (int col = 0; col < width; col++) {

                 fileArray[row][col] = scan.nextInt();
                 System.out.print("(" + row + " ," + col +"): " + fileArray[row][col]+ " ");

             }

             System.out.println();
         }
         dis.close();


    }

}

任何建议将不胜感激。

【问题讨论】:

    标签: java java.util.scanner


    【解决方案1】:

    您已经关闭了 scan 对象正在使用的 InputStream,然后又打开了另一个。毫不奇怪,scan 对象已用完可供读取的整数。它可能会在您关闭它之前缓冲一些输入流,这就是它完成读取较小文件但在较大文件上失败的原因。

    您需要根据稍后打开的新输入流创建一个新的Scanner 对象。

    【讨论】:

    • 谢谢!我错过了那一行,一旦我摆脱它就可以了。
    猜你喜欢
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    相关资源
    最近更新 更多