Tommon
Tommon

Reputation: 29

use loops and random char in arrays java

I'm trying to make a table of 12 by 12 in Java that will choose a random letter(From the ones given) and then output it on the table, however i can't get this to work. Please help...This is what my code looks like:

import java.util.Random;

public class PlayingArea {
public static void main(String[] args){
    String letters= "EFGH"; 
    int N = letters.length(); 
    Random r = new Random(); 
            char [][] letter = new char[12][12]; 
    for (int j = 0; j < letter.length; j++){
        for(int i=0; i < letter.length; i++) {
            letter[i][j] = letters.charAt(r.nextInt(N)) ; 
        }
    }       

    System.out.print(letter); 
}

}

Upvotes: 0

Views: 897

Answers (2)

Cruncher
Cruncher

Reputation: 7812

The algorithm looks fine to me, I think the problem you may be getting is not printing the proper string represention of the array. You can try changing your print statement to something like this

System.out.print(Arrays.deepToString(letter));

Or a little more manually with(Thanks @Joop Eggen):

for (char[] letterRow : letter) 
    System.out.println(Arrays.toString(letterRow));

This version has the advantage that each sub array is on its own line, rather than all jumbled onto one line and it looks more like a table like you'd hoped.

Output:

[G, E, H, H, H, E, H, F, F, E, H, G]
[E, H, H, H, F, G, E, F, H, F, G, H]
[H, F, G, F, F, F, H, G, G, H, H, G]
[E, E, H, E, F, H, E, F, G, F, F, F]
[F, H, F, E, F, H, G, E, H, F, E, G]
[E, H, F, H, H, H, H, E, G, F, F, E]
[H, G, G, G, H, F, G, E, G, H, E, G]
[H, H, E, E, E, E, G, G, H, H, F, F]
[H, F, F, G, G, G, H, H, H, F, E, H]
[H, H, F, E, G, G, H, E, E, E, F, H]
[H, H, G, F, G, F, G, E, H, F, H, F]
[E, F, E, F, F, F, H, E, G, E, F, E]

Upvotes: 4

Akira
Akira

Reputation: 4071

Your problem seems to be here:

letters.charAt(r.nextInt(N)) ;

You need to limit the number returned by nextInt() to the length of your string:

letters.charAt(r.nextInt(letters.length())) ;

Upvotes: -1

Related Questions