简体   繁体   中英

Changing the value of a field String variable

I'm currently working on a version of hangman through java. I've recently been stumped by a problem that I can't seem to solve.

I have an array easyDifficulty and a String hiddenWord . I want to make it so that every time the game starts, my method randomWord() will choose a random word from array easyDifficulty to start the program. Many of my methods use hiddenWord so I pasted all of my code below incase you need to check that. Otherwise, the main parts that I feel like that are causing problems are in the area where I declare my field variables, my randomWord method, and the main method.

import java.util.Arrays;
import java.util.*;
import java.util.Scanner;

public class HangmanGame {

static String[] easyDifficulty = new String[]{"orange", "jacket","shirt"
    ,"rocket","airplane","circle","balloon","swing","truck","caterpillar"};
static Random rand = new Random();

static String hiddenWord = new String("");
static char[] hiddenWordToChar = hiddenWord.toCharArray();
static int triesLeft = 6;
static boolean done = false; 
static int length = hiddenWord.length();
static Scanner input = new Scanner(System.in);
final static int maxLength = 30;
static char[] repeatChecker = new char[30]; //this is to help prevent the user from putting the same char multiple times
static char[] fillWord = new char[length];
static int var;
static int var2;
static char underscore = '_';

static int chooseDifficultyInt;


public static String randomWord(int n) {
    int randomNum = rand.nextInt(9);
    int difficultyInt = n;
    if (difficultyInt == 1){
        //System.out.println(easyDifficulty[randomNum]);
        return easyDifficulty[randomNum];
    }
    return null;


}



public static boolean contains(char[] arr, char i) {
      for (char n : arr) {
         if (i == n) {
            return true;
         }
      }
      return false;
   }

public static boolean multiLetter(char[] arr, char i){
    int multiple = 0;
    for (char n : arr){
        if (i == n){
            multiple++;

            //continue;
        }
    }
    System.out.println(multiple);
    if (multiple > 1){
        return true;
    }
    else {
        return false;
    }

}
public static void createSpaces(int n){
    for (int i = 0; i <= n-1; i++){
        fillWord[i] = underscore;
    }
    System.out.println(fillWord);
}

public static void tryAgain(){
    System.out.println("Would you like to try again? Enter Y/N to go again or quit!");
    char goAgain = input.next().charAt(0);
    goAgain = Character.toLowerCase(goAgain);
    if (goAgain == 'y') {
        triesLeft = 6;
        repeatChecker = new char[20];
        main(null);
    }
    else if (goAgain == 'n') {
        System.out.println("Bye!");
        System.exit(0);
    }
    else {
        System.out.println("Invalid input");
        tryAgain();
    }

}


public static void arrayLetters(){
    System.out.println("This is a " + length + " letter word. Please enter a letter to guess: ");
    char charInput = input.next().charAt(0);
    char[] letters = new char[20];
    //This code only runs if the user inputs a letter that repeats 
    //throughout hiddenWord
    if (multiLetter(hiddenWordToChar, charInput)){
        for (int n = 0; n < length; n++){
            char multiWordLetter = hiddenWord.charAt(n);
            letters[n] = multiWordLetter;
            if (letters[n] == charInput){
                fillWord[n] = charInput;

            }

            if (contains(repeatChecker, charInput)){
                System.out.println("You already did that word, try again!");
                arrayLetters();
            }

            if (Arrays.equals(fillWord, hiddenWordToChar)){
                System.out.println("Congratulations, you win! The word was '" + hiddenWord + "'!");
                System.out.println("You completed the challenge in " + triesLeft + " tries! \n\n");
                tryAgain();
            }
        }
        System.out.println(fillWord);
        System.out.println("Nice! There is a(n) " + charInput + " in this word!");
        System.out.println("You have " + triesLeft + " tries left!\n");
        arrayLetters();
    }


    //This block of code runs when the user input a letter that only occurs once
    //in hiddenWord

    for (int i = 0; i < length; i++){
        char wordLetter = hiddenWord.charAt(i);
        letters[i] = wordLetter;
        if (contains(letters, charInput)){
            /*
            if (multiLetter(letters, charInput)){
                System.out.println("aylmao");
            }
            */
            //System.out.println(multiLetter(hiddenWordArray, charInput));
            if (contains(repeatChecker, charInput)){
                System.out.println("You already did that word, try again!");
                arrayLetters();
            }
            repeatChecker[var] = charInput;
            var++;
            fillWord[i] = charInput;
            if (Arrays.equals(fillWord, hiddenWordToChar)){
                System.out.println("Congratulations, you win! The word was '" + hiddenWord + "'!");
                System.out.println("You completed the challenge in " + triesLeft + " tries! \n\n");
                tryAgain();
            }
            System.out.println(fillWord);
            System.out.println("Nice! There is a(n) " + charInput + " in this word!");
            System.out.println("You have " + triesLeft + " tries left!\n");
            arrayLetters();

        }
        if (i == length-1){
            System.out.println("There is no " + charInput + " in this word!");
            triesLeft--;
            System.out.println("You have " + triesLeft + " tries left!\n");
            if (triesLeft <= 0){ 
                System.out.println("You failed!\n\n");
                tryAgain();

            }
            arrayLetters();

        }
    }


}

public static void main(String[] args) {
    System.out.println("Welcome to my hangman game!");
    System.out.println("Please input your prefered difficulty level.");
    System.out.println("1. Easy");
    System.out.println("2. Medium");
    System.out.println("3. Hard");
    chooseDifficultyInt = input.nextInt();
    randomWord(chooseDifficultyInt);
    hiddenWord = randomWord(chooseDifficultyInt);
    createSpaces(length);
    arrayLetters();
}

}

I'm an intermediate in java programming so I've learned that Strings are immutable. Thus I've considered that the reason why hiddenWord won't be set equal to randomWord(chooseDifficultyInt); is because of that?

I'm an intermediate in java programming so I've learned that Strings are immutable

This often causes confusion among new programmers. This is correct, Strings are immutable. However the variable that points to that String can be re-assigned (assuming it isn't final ) .

You can modify your hidden word as many times as you like:

HangmanGame.hiddenWord = "MyNewWord";
HangmanGame.hiddenWord = "AnotherWord";
HangmanGame.hiddenWord = "ThisWorks";

You might be wondering how the hiddenWord is changing if Strings are immutable.

Your variable isn't actually changing. Every time you re-assign it, a new String is being created. This means that the Strings themselves are never modified.


So yes, you can call

HangmanGame.hiddenWord = HangmanGame.randomWord(n);

and it will work perfectly.

Your initialization of hiddenWord as new String(""); is useless. You could remove it safely.

When you do that:

hiddenWord = randomWord(chooseDifficultyInt);

you set hiddenWord to the reference of a random string of your predefined list, not allocating anything, just reusing an existing string reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM