簡體   English   中英

使用Scanner.nextInt()的Java NoSuchElementException

[英]Java NoSuchElementException using scanner.nextInt()

我試圖讀取pgm文件(512x512數組),當我讀取較大的文件時,出現錯誤:讀取元素(3,97)時出現java.util.NoSuchElementException

我創建了一個小得多的文件來讀取(23x23),它看起來不錯。 有尺寸限制嗎? 我已經檢查了文件,並確認該值有一個整數:這似乎是它崩潰的那一行:

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();


    }

}

任何建議將不勝感激。

您已經關閉了scan對象正在使用的InputStream,然后打開了另一個。 不足為奇的是, scan對象用完了要讀取的整數。 在關閉輸入流之前,它可能會緩沖一些輸入流,這就是為什么它完成讀取較小文件但對較大文件失敗的原因。

您需要根據稍后打開的新輸入流創建一個新的Scanner對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM