Taylor
Taylor

Reputation: 45

In Java my array seems to only store my last added value

Hi I am fairly new at this as you can see but I am trying to make a very basic hang man game. If the users guess is correct I would like to make an array of what letters he has got right so far. But all I get is the last keyboard input saved in the array.

Here is the code.

do {
    System.out.println("Choose a letter: ");
    firstGuess = keyboard.next();
    String [] GuessedWordSoFar = new String[wordToGuess.length()];  
    char[] wordToGuessInCharArray = wordToGuess.toCharArray();  

    if((new String(wordToGuessInCharArray).contains(firstGuess))){
        int index = -1;
        char c = firstGuess.charAt(0);
        for(int z = 0; (z <wordToGuessInCharArray.length)&& 
           (index == -1); z++){ 

            if( wordToGuessInCharArray[z] == c) {
                index = z;
                System.out.println("Correct");
                GuessedWordSoFar[index] = firstGuess;
            }
        }
        System.out.println(Arrays.asList(GuessedWordSoFar));
    }

Upvotes: 0

Views: 102

Answers (1)

kjmikkel
kjmikkel

Reputation: 26

The problem is that the initialization of the GuessedWordSoFar array is inside the do-while loop, so it gets reset each time the loop executes. Try the code below, this should fix your error.

String [] GuessedWordSoFar = new String[wordToGuess.length()];
do {
System.out.println("Choose a letter: ");
firstGuess = keyboard.next();

char[] wordToGuessInCharArray = wordToGuess.toCharArray();

if((new String(wordToGuessInCharArray).contains(firstGuess))){
    int index = -1;
    char c = firstGuess.charAt(0);
    for(int z = 0; (z <wordToGuessInCharArray.length)&& 
       (index == -1); z++){ 

        if( wordToGuessInCharArray[z] == c) {
            index = z;
            System.out.println("Correct");
            GuessedWordSoFar[index] = firstGuess;
        }
    }
    System.out.println(Arrays.asList(GuessedWordSoFar));
}

Upvotes: 1

Related Questions