【问题标题】:Problems with Boolean Array in Self-Avoiding Random Walk Program?自避免随机游走程序中布尔数组的问题?
【发布时间】:2015-02-14 01:50:07
【问题描述】:

我的程序使用 StdDraw 创建一个 N×N 网格。我应该在命令行中接受 N 和 T(N 是网格中的行数,T 是我可以尝试在随机游走中逃离网格的次数)。我不断收到一条错误消息:

Exception in thread "main" java.lang.NegativeArraySizeException
at RandomWalk.main(RandomWalk.java:28)

我的程序如下所示:

import java.util.Random;
    public class RandomWalk {
        public static void main(String[] args) {
            int N = Integer.parseInt(args[0]); 
            int T = Integer.parseInt(args[1]); 
            int tempN = N;
            int DEcount = 0; //Dead End Count
            int x0 = N/2;
            int y0 = N/2;
            int x1 = x0;
            int y1 = y0;
            StdDraw.setXscale(0.0, N);
            StdDraw.setYscale(0.0, N);
            StdDraw.setPenColor(StdDraw.GRAY);
            StdDraw.setPenRadius(0.002);
            while (N >= 0) {
                StdDraw.line(tempN, N, 0, N); 
                N--;
            }
           StdDraw.setPenColor(StdDraw.GRAY);
           StdDraw.setPenRadius(0.002);
           N = tempN;
           while (N >= 0) {
               StdDraw.line(N, tempN, N, 0); 
               N--;
           }
           for (int i = 0; i < T; i++) {
               boolean[][] check = new boolean[N][N];
               while (x1 > 0 && x1 < N-1 && y1 > 0 && y1 < N-1) {
                   //check for dead ends and make a random move
                   check[x1][y1] = true;
                   if (check[x1-1][y1] && check[x1+1][y1] && check[x1][y1-1] && check[x1][y1+1]) {
                DEcount++;
                break;
            }
            double rand = Math.random();
            if      (rand < 0.25) { if (!check[x1+1][y1]) x1++;}
            else if (rand < 0.50) { if (!check[x1-1][y1]) x1--;}
            else if (rand < 0.75) { if (!check[x1][y1+1]) y1++;}
            else if (rand < 1.00) { if (!check[x1][y1-1]) y1--;}

            StdDraw.setPenColor(StdDraw.RED);
            StdDraw.setPenRadius(0.01);
            StdDraw.line(x0, y0, x1, y1);
            x0 = x1;
            y0 = y1;
            }
         }
    }
}

此外,我应该在网格上打印的内容(代表随机游走的红线)没有打印。不过,网格本身确实会打印。

谁能帮我弄清楚我做错了什么?

感谢您的帮助。

【问题讨论】:

    标签: java random boolean random-walk stddraw


    【解决方案1】:

    考虑这个代码片段:

           while (N >= 0) {
               StdDraw.line(N, tempN, N, 0); 
               N--;
           }
           for (int i = 0; i < T; i++) {
               boolean[][] check = new boolean[N][N];
    

    在 while 循环结束时,N 为 -1,然后将其用作数组大小。

    您可能打算使用tempN,它似乎保留了N。我建议使用更具描述性的名称来避免此类问题。

    【讨论】:

      【解决方案2】:
      • 问题 1:在您的 while 循环中,您将变量 N 递减,直到其 -1。它的下一个用途是在分配check 时作为数组大小说明符。我猜你在 for 循环之前忘记了另一个分配 N = tempN

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-02
        • 1970-01-01
        相关资源
        最近更新 更多