0

I'm writing a program similar to hangman. I need to set the length of an array of '-'s to the length of the word input. I've got the length of the and i've got the array i just can't figure out how to "combine them" in a manner of speaking.

public static char[] initializeDisplay(char[] wordToGuess) {
    int len=wordToGuess.length;
    System.out.print(len);
    char[] charArray ={ '-' };
    return charArray;
}
2
  • Please read this guide before asking another question. When asking a question you should at least make some attempt at solving the problem. If it doesn't produce the correct output at least you tried. Commented Feb 10, 2018 at 0:34
  • This is as far as I got. All attempts to proceed further ended in compiling errors. There was no output produced Commented Feb 10, 2018 at 0:39

2 Answers 2

3

Arrays are immutable, which means that they cannot be increased or decreased in size after creation. Set the length on initialization as follows :).

   public static char[] initializeDisplay(char[] wordToGuess) {
       /* No need to store the length
       int len=wordToGuess.length;
       System.out.print(len);
       char[] charArray ={ '-' }; */

       // Pre-define the length at initialization 
       char[] charArray = new char[wordToGuess.length];

       // Fills the array with the char '-' 
       Arrays.fill(charArray, '-');

       return charArray;

   }
Sign up to request clarification or add additional context in comments.

Comments

0

Since you don't know number of elements in the wordToGuess in advance, you can't use Array Initializer: https://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html#jls-10.6

You should create new char array instead and fill in each element one by one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.