【问题标题】:What's Wrong With My Load Data Method?我的加载数据方法有什么问题?
【发布时间】:2012-01-28 20:07:10
【问题描述】:

这是我用来从文件加载保存的游戏数据的方法。因为这个,我在某个时候得到了一个叫做 error15 的东西。谷歌上出现的唯一事情是与 http 有关,但那不可能,因为我没有做那样的事情。当对象将字符串打印到控制台时,它会完成第一行保存的数据,但不会继续读取其他数据。我有一种预感,这可能与我对 in.nextLine(); 的使用有关(还有其他我应该使用的东西吗?)如果有人能告诉我我做错了什么,我会永远爱你。

/**
 * Returns a 2-dimensional 15*15 array of saved world data from a file named by x and y coordinates
 */
public String[][] readChunkTerrain(int x, int y)
{
    String[][] data = new String[15][15]; //the array we will use to store the variables
    try {
        //initiate the scanner that will give us information about the file
        File chunk = new File( "World/" + x + "." + y + ".txt" );
        Scanner in = new Scanner(
                new BufferedReader(
                    new FileReader(chunk)));

        //go through the text file and save the strings for later
        for (int i=0; i<15; i++){
            for (int j=0; j<=15; j++){
                String next = in.next();
                data[i][j] = next;

                System.out.println(i + j + next); //temporary so I can see the output in console
                System.out.println();
            }
            in.nextLine();
        }

        in.close(); //close the scanner
    }
    //standard exception junk
    catch (Exception e)
    {System.err.println("Error" + e.getMessage());}

    return data; //send the array back to whoever requested it
}

【问题讨论】:

    标签: java file-io java.util.scanner filereader


    【解决方案1】:

    你得到的 15 的错误(你应该已经发布了顺便说一句,并且会立即得到答案)可能是一个 ArrayIndexOutOfBoundsException,因为你尝试在你的循环中访问 data[i][15],它不存在。

        for (int i=0; i<15; i++){
            for (int j=0; j<=15; j++){
    

    您的j 循环应调整为匹配i 循环,因为您的data 变量初始化为new String[15][15]。所以将其转换为以下内容,一切都会起作用

            for (int j=0; j<15; j++){
    

    注意&lt; 而不是&lt;=

    【讨论】:

    • 非常感谢;那行得通!我实际上确实发布了错误。它只是说“error15”。
    • 这要归功于您糟糕的错误处理。 System.err.println("Error" + e.getMessage()) 没有打印出太多信息。至少打电话e.printStackTrace()这样你就知道错误发生在哪里以及它是什么类型的错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 2019-10-30
    • 1970-01-01
    相关资源
    最近更新 更多