DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

# Thread: Generating a random binary array

1. Registered User
Join Date
Dec 2005
Posts
4

## Generating a random binary array

I'm new to java so it is possible i haven't spotted something simple here but its been bugging me for hours so here goes.

I've written a class that creates an array of ones and zeros at random and then prints this in the command line (or should do).

My code:
class Genpop {
public static int[][] genpop1() {
int[][] population = new int[8][8];
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
double x = java.lang.Math.random();
if (x<0.5){
population[i][j]=0;}
else{
population[i][j] =1;}
}
}
return population;
}
public static void main(String args[]) {
int[][] pop = genpop1();
System.out.println(pop);
}
}

I've tried print lines to check that the random number is being generated and to make sure that the if statements are being executed but all i get when i run the program is:

[[I@f4a24a

not very nice

any help would be greatly appriciated
cheers

2. Registered User
Join Date
Dec 2005
Posts
4

## getting there...

i have nearly solved my own problem

replacing: System.out.println(pop)
with:
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
System.out.println(pop[i][j] + " ");
}
System.out.println();
}

However this outputs the zeros and ones in one long vertical line, i would prefer them in a square as if i were just just printing the array instead of eac individual element.

Any tips greatfully accepted

3. Registered User
Join Date
Dec 2005
Posts
4

## solved

replace System.out.println(pop[i][j] + " ")
with System.out.print(pop[i][j] + " ")

sorry about abuse of message board
just a beginner

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise