MicroFarad
MicroFarad

Reputation: 13

2 boolean check aren't compatible

Trying to create a method that will make an array and assign different numbers from 1 - 9 to each index of the array (nos. cannot be repeated). please have a look at the boolean comparison i made, this is where the cmd stuck at runtime. I have tried to separate the two but nothing happens.

Please help.

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());
  }
 }

Upvotes: 1

Views: 68

Answers (3)

Vinay Prajapati
Vinay Prajapati

Reputation: 7504

You are doing it wrong or unknowingly actually at several places:

  1. & and && are two different things. Use && when you want to continue to check for second condition iff first operand or condition evaluates to true otherwise to evaluate both operands use &.

  2. Why multiplying by 9. Multiply it by 10. As multiply by 9 constrained to 1-8 numbers only.

  3. Why are you printing the grid within a loop and having a special loop for same?. Just print the grid it will show you all the elements.

Below is your corrected program:

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());
  }
}

Hope it helps!

Upvotes: 0

WalterM
WalterM

Reputation: 2706

I agree with Matt Ball, create an array 1-9 and shuffle, but to answer your question, the problem is here:

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

Should be this:

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

since you multiply Math.random() * 9 you will only get numbers between 0-8, adding 1 will give you 1-9.

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359786

Why not use a Fisher-Yates shuffle instead?

That is, fill the array with 1-9 and then Collections.shuffle() it.


Aside: use && not & in your original code.

Upvotes: 1

Related Questions