2 布尔检查不兼容

2 boolean check aren't compatible

正在尝试创建一个方法来创建一个数组并将 1 - 9 中的不同数字分配给数组的每个索引(编号不能重复)。 请看一下我所做的布尔比较,这是 cmd 在运行时卡住的地方。我试图将两者分开,但没有任何反应。

请帮忙。

import java.util.ArrayList;

class Testing {

public static void main (String[] args) {

  ArrayList<Integer> grid = new ArrayList<Integer>();

     int randNum;
     int count = 0;
     int size=8;

     for (int b = 0; b <=size; b++) { 

       while (count <= size) {

        randNum = (int) (Math.random() * 9);


           if (grid.contains(randNum) == false & randNum != 0 ) { 

            grid.add(randNum);
            count++;

          }
       }
     System.out.println(grid.get(b)); 
    }
   System.out.println("size: " + grid.size());
  }
 }

为什么不使用 Fisher-Yates shuffle 呢?

即用1-9填充数组,然后Collections.shuffle()它。


旁白:在您的原始代码中使用 && 而不是 &

我同意 Matt Ball 的观点,创建一个数组 1-9 并随机播放,但要回答你的问题,问题就在这里:

randNum = (int) (Math.random() * 9);
if (grid.contains(randNum) == false & randNum != 0 ) { 

应该是这样的:

randNum = (int) (Math.random() * 9) + 1;
if (grid.contains(randNum) == false) {

因为你乘 Math.random() * 9 你只会得到 0-8 之间的数字,加 1 会得到 1-9.

你实际上在几个地方做错了或在不知不觉中做错了:

  1. & 和 && 是两个不同的东西。当您想继续检查第二个条件时使用 && 当第一个操作数或条件评估为 true 否则评估两个操作数使用 &.

  2. 为什么乘以9。乘以10。因为乘以9仅限于1-8个数字。

  3. 为什么要在循环中打印网格并为此设置一个特殊循环?。只需打印网格,它就会显示所有元素。

以下是您更正后的程序:

import java.util.ArrayList;

public class HelloWorld{

     public static void main(String []args){
        ArrayList<Integer> grid = new ArrayList<Integer>();

     int randNum;
     int count = 0;
     int size=8;

       while (count <= size) {
        randNum = (int) (Math.random() * 10);
        System.out.println(randNum+"test"+grid); 
           if (!grid.contains(randNum) && randNum != 0 ) { 
               System.out.println("grid coming in here"+grid); 
            grid.add(randNum);
            count++;

          }
       }
     System.out.println(grid); 
   System.out.println("size: " + grid.size());
  }
}

希望对您有所帮助!