检查int []是否包含int

问题描述 投票:0回答:1

出于某种原因,我的脚本正在无限循环,我无法弄清原因。我有一个包含40个棋子的数组,需要将它们随机放在板上。所以我有一个随机数,它从数组中选择一个随机的pawn,但是如果已经选择了pawn,它就必须选择一个新的随机数,但是由于某种原因,最后一部分似乎是错误的。而且我不知道为什么。

Random rand = new Random();    

    int[] availablePawnsArray = {1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 11, 12, 12, 12, 12, 12, 12 };
    // this array contains 40 integers

    int[] chosenPawns = new int[40];
    //this array contains the index numbers of already selected pawnsfrom the previous array

    int counter = 0;
    //counts how many pawns have been selected already    

    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 10; j++) {
        //this refers to my board, 40 locations for my 40 pawns    

            int chosenPawn = rand.nextInt(40);
            //a random numder from 0 to 40

            boolean found = false;
            //a boolean to say if i have already selected this pawn before or not    

            do {
               for (int n : chosenPawns) {
                   if (n == chosenPawn) {
                       found = true;
                       chosenPawn = rand.nextInt(40);
                   } else {
                       found = false;
                   }
               }
            } while(found == true);    

            board[i][j].rank = availablePawnsArray[chosenPawn];
            chosenPawns[counter] = chosenPawn;
            counter++;
        }
    }
java arrays random infinite-loop do-while
1个回答
0
投票

您可以有两个数组,第二个数组保留选定的整数,然后在第二个数组中循环检查是否有等于给定一个的数字返回false或true。

int [] selectedInts = new int[40];

boolean contains(int num) {
  for (int i = 0 ; i < selectedInts.length; i++) {
    if (i == num) return true;
  }
  return false;
}

也可以使用像

Arrays.asList().contains(yourInt);
© www.soinside.com 2019 - 2024. All rights reserved.