简体   繁体   中英

What's Wrong With My Load Data Method?

This is a method I'm using to load saved game data from a file. I'm getting something called error15 at some point because of this. The only thing that came up on Google was something to do with http, but that can't be it because I'm not doing anything like that. When the object prints the strings to the console, it completes the first line of saved data but doesn't go on to read the others. I have a hunch it might have to do with my use of in.nextLine(); (is there something else I should be using instead?) If anyone can tell me what I'm doing wrong I will love you forever.

/**
 * 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
}

The error with the 15 you get (which you should have posted BTW, and would resulted in an immediate answer) is probably an ArrayIndexOutOfBoundsException since you try to access data[i][15] in your loop, which does not exists.

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

Your j loop should be adjusted to match the i loop as your data variable is initialized as new String[15][15] . So convert it to the following and all will work

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

Note the < instead of <=

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM