简体   繁体   中英

Adding Char to Char Array in Java

I'm still pretty new to Java so bear with me. I'm making a simple hangman game that takes input from the user. I am trying to append the guessed letter to the knownLetters array but I get a type mismatch. I tried .concat() and got the same type error. Here is where I am now. Any ideas or documentation resources (that a novice can read) would be helpful. Thanks!

Edit: Thanks for the comments, everyone! These are very helpful.

 public static boolean updateWithGuess(char[] knownLetters,
                                      char guessedLetter,
                                      String word) {

    System.out.println(Arrays.toString(knownLetters));

    int i = 0;
    while(word.indexOf(i, guessedLetter) != -1) {
      i = word.indexOf(i, guessedLetter) + 1;
      knownLetters += guessedLetter;

Using arrays in that case is not the best choice because arrays have a fixed size and you cannot dynamically add and remove items, maybe rather choose lists.

If you need a simple introduction, here you are:
https://www.geeksforgeeks.org/list-interface-java-examples/

Others have mentioned StringBuilder and List which are a step in the right direction as they dynamic (in number of elements). However since this question is only concerned with keeping track of each letter that was guessed a set makes the most sense. One common example is HashSet . Sets do not allow duplicates. However sets will allow both the upper and lower case versions of a character to be present in the set (since they have different values). So you could normalize all the guesses and known letters to either uppercase or lowercase.

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