【问题标题】:Trying to create a minesweeper like game placing random mines with user input using 2d array尝试创建一个类似于游戏的扫雷游戏,使用 2d 数组放置随机地雷和用户输入
【发布时间】:2018-04-12 11:40:39
【问题描述】:

我试图创建一个类似于扫雷的模拟,当 0 是清晰的并且 X 是一个地雷时,用户输入地雷的数量并使用随机生成器将其放置在 2D 数组中。当我运行它时,网格打印但我得到 java.lang.ArrayIndexOutOfBoundsException: 4 并且不知道如何修复它。我以前从未使用过二维数组。

   import java.util.Scanner;
   import java.util.Random;

  public class Minesweeper {


          private  static  int count = 0;  /* used to count the number of mines */

         public static void main ( String [] args) {

              int r = 12;
              int c = 12;
              int ground [][] = new int [r][c]; //2D array 12 x 12 
              int a = 0;  // variable to print 0's as an integer instead of a string 


                    Scanner sc=new Scanner(System.in); // scanner for the user to input number of mines 

        System.out.print("Enter mines: ");
        Random myRandom = new Random();
        int N; // N is the variable for the number of mines 
        N = sc.nextInt(); // scanner to input the number 

        for (int k = 0; k < ground.length; k++) { // nested loop to print a 12 x 12 grid

             for (int j = 0; j < ground.length; j++) {
               System.out.print(" " + a + " " ); // prints the 0s

          }
                System.out.println();
      }


        while(count <=  N) { // loop to count the mine numbers the user chose
                         /* if count < N, we need to put more mines */


                        do {
                                 r = myRandom.nextInt(12); // generate the mines in random places
                                 c = myRandom.nextInt(12);

                        }   while(mineOrNot(r, c) == false);


                       count += 1;// count to place the right amount of mines 
        }


    }

// function to make sure no 2 mines are in the same location 
        public  static  boolean  mineOrNot(int r, int c) {
            int ground [][] = new int [r][c];
           // if theres no mines its ok to place one 
         if(ground[r][c] == 0) {
             ground[r][c] = 1; // it is ok, put a mine at here 
             return true;
         }
         else 
           return false;
           }

  }

【问题讨论】:

    标签: arrays 2d minesweeper


    【解决方案1】:

    由于我不会使用 Java 编写代码,因此我只能向您介绍为什么会收到此错误的基本信息。这基本上是从数组开始的通行权,即使是经验丰富的程序员在某些情况下也会时不时遇到这个问题。

    Array Indexing in Java

    基本上,您正在尝试访问该数组的一部分,该部分在您为其设置的范围内不存在。

    例如您正在访问元素 13,null,并尝试使用它,导致错误。

    如果可以的话(不要使用 Java,我想 Oracle 有这个功能)抛出一个断点并逐步执行每次迭代并尝试准确计算数组上的滴答声。

    它应该保持在 0 - 11 之间,因为 Java 中的数组索引从 0 开始。

    所以你的 1 - 12 个单元格成为索引

    0 - 11.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-15
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      • 2015-11-19
      • 2021-02-28
      • 2013-04-11
      相关资源
      最近更新 更多