1

.txt ファイルのスキャンに関連して、例外 NoSuchElement が引き続き発生します。例外の原因となるエラーは次のとおりです。

"java.util.Scanner.throwFor(Unknown Source)
 java.util.Scanner.next(Unknown Source)
 java.util.Scanner.nextInt(Unknown Source)"

私が行っているのは、ASCII 端末ゲームの基本マップのテストとして 1 と 0 を読み取ることだけです。

私のコード:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Adventure {
    private Scanner in_file;
    private char[][] level;
    public Adventure() {
        level = new char[5][5];
    }
    public static void main(String []args) {
        Adventure adv = new Adventure();
        adv.load_game();
        adv.main_game();
    }
    public void load_game() {
        try {
            in_file = new Scanner(new File("level.txt"));
        } catch (FileNotFoundException e) {
            System.err.println("ERROR: Level could not be loaded!");
            System.exit(1);
        }
        for (int i = 0; i < level.length; i++ ) {
            for (int j = 0; j < level[i].length; j++) {
                if (in_file.hasNextInt()) {
                    if (in_file.nextInt() == 0) 
                        level[i][j] = '-';
                    else if (in_file.nextInt() == 1)
                        level[i][j] = '#';
                }
            }
        }
        in_file.close();
    }
    public void new_game() { 

    }
    public void main_game() {
        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 50; j++) {
                System.out.print(level[i][j]);
            }
        }
    }
    public void save_game() {

    }
}

私のテキストファイル「level.txt」:

    11111
    10001
    10001
    10001
    11111
4

1 に答える 1

2

以下のコードでは、1 つではなく 2 つの int を読み取ります。

if (in_file.hasNextInt()) {
    if (in_file.nextInt() == 0) 
        level[i][j] = '-';
    else if (in_file.nextInt() == 1)
        level[i][j] = '#';
}

これでNoSuchElementException問題は解決するはずです:

if (in_file.hasNextInt()) {
    int nextInt = in_file.nextInt();
    if (nextInt == 0) 
        level[i][j] = '-';
    else if (nextInt == 1)
        level[i][j] = '#';
}

ただし、int をそれを構成する数字に分割する必要もあります (たとえば、10、100、1000 などで分割して丸めるか、int を String に入れることでそれを行うことができます)。

于 2012-07-13T14:01:05.337 に答える