我目前正在做一個數組項目,在我的介紹CS類,我必須成功地做一個hang子手遊戲。我認爲我開始的時候相當合適,但我似乎無法掌握如何將字符替換爲字符串。我必須有一種方法來創建一個隨機單詞,所以這就是爲什麼我在我的代碼中有一個方法。看看我到目前爲止:如何獲得一個字符替換字符串中的部分(java)
import java.util.Random;
import java.util.Scanner;
public class ProjectNum2 {
//creator's name
public static void main(String[] args) {
System.out.println("Welcome to the Hangman Word game!");
String[] wordKey = {
"loop",
"for",
"while",
"java",
"switch",
"scanner",
"else",
"double",
"integer",
"public",
"static",
"method",
"return",
"null",
"void",
"true",
"false",
"import",
"string",
"character"
};
String[] wordSpace = {
"_ _ _ _",
"_ _ _",
"_ _ _ _ _",
"_ _ _ _",
"_ _ _ _ _ _",
"_ _ _ _ _ _ _",
"_ _ _ _",
"_ _ _ _ _ _",
"_ _ _ _ _ _ _",
"_ _ _ _ _ _",
"_ _ _ _ _ _",
"_ _ _ _ _ _",
"r _ _ _ _ _",
"_ _ _ _",
"_ _ _ _",
"_ _ _ _",
"_ _ _ _ _",
"_ _ _ _ _ _",
"_ _ _ _ _ _",
"_ _ _ _ _ _ _ _ _"
};
char[] letters = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
final int guesses = 6;
int index = 0;
index=(int) randomGen(wordKey, wordSpace);
Scanner keyboard = new Scanner(System.in);
System.out.println();
System.out.print("Choose a letter or enter zero to guess the word: ");
char letter = keyboard.nextLine().charAt(0);
}
private static Object randomGen(String[] wordKey, String[] wordSpace) {
String gameWord;
Random randIndex = new Random();
int index = randIndex.nextInt(wordKey.length);
gameWord = wordSpace[index];
System.out.print(gameWord);
return (index);
}
}
字符串在Java不變 – 2014-10-30 20:30:56
你有一個體面的開始,你需要使用一個循環來獲得多個用戶輸入,直到他們贏或輸... – brso05 2014-10-30 20:32:39
@Alex你可以使用一個字符數組而不是一個StringBuilder(我假設你沒有覆蓋StringBuilder)。 – brso05 2014-10-30 20:33:39