我试图将1D字符串数组随机放置到2D char数组中,但是我的for循环遇到问题。 userWords是String的一维数组,而puzzleBoard是char的2D数组。
我尝试过
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
所以我尝试了
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);
}
,但它仅将3个char而不是3个char字符串打印到char数组中。
我也尝试过
puzzleBoard[r][c] = userWords[i].toCharArray();
代替
puzzleBoard[r][c] = userWords[i].charAt(i);
但是它显示错误“无法从char []转换为char”
谢谢
完整代码
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
答案 0 :(得分:3)
您可以尝试以下一种方法:
for (int i = 0; i < userWords.length; i++) {
int r = rand.nextInt(puzzleBoard.length);
int c = rand.nextInt(puzzleBoard[r].length - userWords[i].length());
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r][c + j] = userWords[i].charAt(j);
}
}
并且您应该添加一些东西来检测此位置是否已经有单词,否则,如果随机数指向已经写入单词的位置,则将其覆盖。
答案 1 :(得分:1)
我认为您应该使用2个for循环,因为您要先选择字符串,然后再选择字符串中的字符。
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r][c + j] = userWords[i].charAt(j);
}
}