Reputation: 79
I am currently doing a array project in my intro CS class and I have to successfully make a game of hangman. I think I am starting it off fairly right, but I can't seem to grasp how to replace a char into a string. I have to have a method to create a random word, so that's why I have a method in my code. Check out what I have so far:
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);
}
}
Upvotes: 0
Views: 176
Reputation: 123400
To get you on the right track while not spoiling all the fun, here's a method that from the string "loop"
and the char 'o'
derives and prints the string _oo_
:
class Test {
public static void main(String[] args) {
String word="loop";
char[] array = new char[word.length()];
for(int i=0; i<array.length; i++) {
array[i] = '_';
}
char guess = 'o';
for(int i=0; i<word.length(); i++) {
if(word.charAt(i) == guess) {
array[i] = guess;
}
}
System.out.println(new String(array));
}
}
Upvotes: 0
Reputation: 564
Strings in Java are immutable, meaning that you cant change it. You have to build a new String object, using in your case for example the String.replace(...) method.
Upvotes: 1
Reputation: 2300
String are immutable which means once you create them you cannot change them. Use a StringBuilder class instead. Here is a simple example to get you started
StringBuilder sb = new StringBuilder(30);
sb.append("Hello Matthew");
// append a character
char c = '!';
sb.append(c);
Upvotes: 0