【问题标题】:Java Scanner: NoSuchElement reading in plaintext file with map made of numerical charactersJava Scanner:没有这样的元素在纯文本文件中读取,地图由数字字符组成
【发布时间】:2012-07-13 13:57:22
【问题描述】:

相对于 .txt 文件的扫描,我不断收到 NoSuchElement 异常。导致异常的此类错误是:

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

我所做的只是读取 1 和 0 作为 ASCII 终端游戏中基本地图的测试。

我的代码:

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

【问题讨论】:

  • Scanner而言,该文件仅包含五个整数:1111110001100011000111111。它不包含整数01 的任何实例。
  • 你应该用空格分隔你的整数(默认Scannerdelimiter)

标签: java terminal ascii java.util.scanner


【解决方案1】:

在下面的代码中,您读取的是 2 个整数而不是 1 个:

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 来做到这一点)。

【讨论】:

  • 没有更多错误,但什么也不会打印出来! (我编辑了嵌套 for 循环的打印以适合我的 5x5 数组)
  • 因为您的整数都不是 0 或 1。请参阅我的最后一个段落和问题下方的 cmets。如果可以的话,用空格分隔文件中的数字应该可以解决问题。
  • 它有效,感谢您的帮助!总的来说,我对 IO 还是很生疏,希望通过努力,我明年在 AP 比赛中会变得更好。 sci.,这只是一些茶歇游戏,以帮助教我的朋友 java。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-30
  • 1970-01-01
相关资源
最近更新 更多