更改字段String变量的值

时间:2016-08-23 12:28:31

标签: java string

我目前正在通过java处理一个版本的hangman。我最近被一个我似乎无法解决的问题所困扰。

我有一个数组easyDifficulty和一个字符串hiddenWord。我希望这样做,以便每次游戏开始时,我的方法randomWord()将从数组easyDifficulty中选择一个随机单词来启动程序。我的很多方法都使用hiddenWord所以我粘贴了所有代码,因为你需要检查一下。否则,我认为导致问题的主要部分是在我声明我的字段变量,randomWord方法和main方法的区域。

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();
}

}

我是java编程的中间人,所以我已经知道字符串是不可变的。因此,我认为将hiddenWord设置为等于randomWord(chooseDifficultyInt);的原因是因为这个原因?

2 个答案:

答案 0 :(得分:1)

  

我是java编程的中间人,所以我已经知道字符串是不可变的

这经常会引起新程序员的混淆。这是正确的,字符串是不可变的。但是,指向String 的变量可以重新分配 (假设它不是final

您可以根据需要多次修改隐藏的字词:

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

如果字符串是不可变的,你可能想知道hiddenWord是如何变化的。

您的变量实际上正在发生变化。每次重新分配它时,都会创建一个新的String。这意味着字符串本身永远不会被修改。

是的,你可以打电话给

HangmanGame.hiddenWord = HangmanGame.randomWord(n);

它会完美运作。

答案 1 :(得分:0)

hiddenWord初始化为new String("");是没用的。你可以安全地删除它。

当你这样做时:

hiddenWord = randomWord(chooseDifficultyInt);

您将hiddenWord设置为预定义列表的随机字符串的引用,而不是分配任何内容,只是重用现有的字符串引用。