简体   繁体   中英

Grid drawing issue/error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Grid.main(Grid.java:25)

The above error occurs when attempting to compile:

class Grid {
// Grid drawing method
    static void drawGrid(int n) {
        StdDraw.setXscale(0, 2*n);
        StdDraw.setYscale(0, 2*n);
// StdDraw.jar setter for scale method called
        for (int v = 1; v <= n; v++) {
            // variable colours lower left square red.
            for (int k = 1; k <= n; k++) {
                if ((v+k) % 2 == 0)
                    StdDraw.setPenColor(StdDraw.RED);
                else
                    StdDraw.setPenColor(StdDraw.BLACK);
                StdDraw.filledSquare(2*v-1, 2*k-1, 1);
            }
        }
    }

    public static void main(String[] args) {
        drawGrid(Integer.parseInt(args[5])); 
        // calls the drawGrid method to draw the grid with defined values
    }
}

I know this can be interpreted as a simple program and a basic error to most of you, just an innocent little red and black grid but it's stumped me. I think I understand what the error means, I'm attempting to access a size of grid the program can't draw? This is what I've gathered from research from resources on this site and others, I just do not understand why a value of 5 is throwing the error. I tried changing that value and it's indiscriminate no matter the number. I think there may be an issue with the increment calculations or something?

This program successfully compiled on Netbeans, according to my colleagues but on my home Eclipse set up I'm getting the "OutOfBounds" error.

Of course, I realise this may be slightly trivial but have done everything I can to understand why my colleagues code is failing, and I can shed little light on it myself either. So, I pose it you, Stack Overflow community. What could be the reasoning for this error?

PS I'm curious if this actually works in Netbeans as I'm taking moderately trustworthy colleagues words for it but, don't have the means to setting up the JDK on this system at the moment. I would be most appreciative if anyone who does have access to the software could test this?

The error appears to be occurring in your main method. args[5] is the 6th command line argument to your program. Based on your code, I'm assuming that it should be drawGrid(Integer.parseInt(args[0])); . This will access the first command-line argument.

As far as whether it works in Netbeans, the only way to find out is to try it!

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