mercredi 13 mars 2019

Randomly place 1D string array into 2D char array

I'm trying to randomly place 1D string array into 2D char array but I'm having issues with my for-loop. userWords is 1D array of String while puzzleBoard is a 2D array of char.

I've tried

for(int i=0; i<userWords.length;i++) {
        puzzleBoard[r++] = userWords[i].toCharArray(); 
    }

but it's not placing it randomly like I want it to

So I tried

    for(int i=0; i<userWords.length;i++) {
        int r = rand.nextInt(ROW) + 1;
        int c = rand.nextInt(COLUMN) + 1;
        puzzleBoard[r][c] = userWords[i].charAt(i);
    }

but it's printing only 3 char instead of the 3 strings of char into the char array.

I've also tried

    puzzleBoard[r][c] = userWords[i].toCharArray();

instead of

    puzzleBoard[r][c] = userWords[i].charAt(i);

But it display error "cannot convert from char[] to char"

Thank you

Full Code

public static void main(String[] args) {
    String[] userWords = new String[3];
    Methods.userInput(userWords); //ask user for input 
    Methods.fillPuzzle(puzzleBoard); //fill the puzzle with random char

    for(int i=0; i<userWords.length;i++) {
        int r = rand.nextInt(ROW) + 1;
        int c = rand.nextInt(COLUMN) + 1;
        puzzleBoard[r][c] = userWords[i].charAt(i);
    }

    Methods.printPuzzle(puzzleBoard); //print out the puzzle

}//end main 


public static void printPuzzle(char a[][]) {

    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[i].length; j++) {
            System.out.print(a[i][j] + " ");
        }
        System.out.print((i+1));
        System.out.println();
    }

}//end printPuzzle

public static void fillPuzzle(char a[][]) {

    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[i].length; j++) {
            a[i][j] = '*';
        }
    }
}//end fillPuzzle

public static void userInput(String a[]) {
    Scanner input = new Scanner(System.in);

    for(int i = 0; i < a.length;i++) {
        System.out.println((i+1) + ". enter word:");
        a[i] = input.next().toUpperCase();
    }
}//end userInput




Aucun commentaire:

Enregistrer un commentaire