java - 为什么我的数组填充不正确?

标签 java arrays text-files

我正在用 Java 编写游戏代码。具体来说,我正在使用由 .txt 文件中的字符填充的字符数组来创建关卡。我的问题是数组没有按应有的方式填充,最后一行仍然为空。我无法解决这个问题,所以任何类型的帮助都会很乐意接受,这是有问题的代码块:

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

char background[][] = new char [14][20];

try {

    FileInputStream fileinput = new FileInputStream("background.txt");
        int r;
        for(int i=0;i<=13;i++){
            for(int j=0;j<19;j++){
                while((r = fileinput.read()) != -1){
                    char c = (char) r;
                    background[i][j] = c;
                    break;
                }
            }
        }
        fileinput.close();
    }

    catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    for (int i=0;i<=13;i++){
        for(int j=0;j<=19;j++){
            System.out.print(background[i][j]);
        }
    }
}

整个代码也可以在以下链接中找到:http://pastebin.com/HtwMpsjm 这也是 .txt 文件!

最佳答案

你不小心犯了你的条件之一,我已经评论了更改的行。

正如有人在评论中提到的,您可能会发现将循环条件视为 for(int i=0;i<20;i++) 是有益的。而不是for(int i=0i<=19;i++)它使代码更具可读性。

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

char background[][] = new char [14][20];

try {

    FileInputStream fileinput = new FileInputStream("background.txt");
        int r;
        for(int i=0;i<=13;i++){
            for(int j=0;j<=19;j++){//<<THIS LINE WAS CHANGED
                while((r = fileinput.read()) != -1){
                    char c = (char) r;
                    background[i][j] = c;
                    break;
                }
            }
        }
        fileinput.close();
    }

    catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    for (int i=0;i<=13;i++){
        for(int j=0;j<=19;j++){
            System.out.print(background[i][j]);
        }
    }
}

关于java - 为什么我的数组填充不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24020851/

相关文章:

JavaFX动态添加按钮

java - Intellij,一次打开两个项目

delphi - TFile.ReadAllText 与 TEncoding.UTF8 省略前 3 个字符

windows - 批处理文件 : "Missing Operator" error while incrementing a value in a textfile?

java - 从 JAR 运行 Main.class,在应用程序框架中显示结果

java - 使用 java poi 从 Office 2007+ 文档中读取属性集

php - 如果数组中已经存在值,则在 PHP 中发出错误

javascript - 如何根据子字段的值对对象数组进行排序?

c - 在二维数组中排列 Char

C# - 从 List3 中删除 List1 和 List2 中的项目时出现问题