1

I am tryiing to make a hangman game in Java, but I am having problems initializing a variable lStorage. I have added String[] lStorage,but still not initializing.

switch(difficulty){
    case 0:
        String[] easywords= new String[]{"integer","project","octopus"};
        int wrong = 12;
        String[] lStorage;
        String easyrnd = (easywords[new Random().nextInt(easywords.length)]);
        System.out.println("The word has " + easyrnd.length() + " Letters");
        while(wrong>=0){
        System.out.println("\n guess a letter");
        String letterguess = consolereader.nextLine();

        if(easyrnd.contains(letterguess)){
            System.out.println("correct " + letterguess + " is the " + "...number" + "Letter"); //need to put in number of letter
            for(int i=12;i>0;i--){
                lStorage[i]=letterguess;
            }
5
  • 1
    Which variable? Which line is failing? I can't see any initialization of the lStorage variable, mind you. Where do you think you assign it a value? Commented Dec 29, 2015 at 16:02
  • 1
    Initializing should be something like : String[] lStorage = new String[12]; Commented Dec 29, 2015 at 16:03
  • String[] lStorage; " it says that the variable hasn't been initialised, even though it has" The variable has been declared, not initialized. Commented Dec 29, 2015 at 16:03
  • You never initialize and define a size for your lStorage array. Commented Dec 29, 2015 at 16:04
  • String[] lStorage; is inside the switch statement, unless you explicitly declare it, it is not initialized. Commented Dec 29, 2015 at 16:04

3 Answers 3

3

The array actually hasn't been initialized. What you've done is declared it. Try something like this:

String[] lStorage = new String[size];

If this array has to be dynamically sized, I would suggest using a java.util.List or another collection class.

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

Comments

0

You need to initialize your String array

Try to change this line

String[] lStorage;

to this one

String[] lStorage = new String[12];

Comments

0

In Java, arrays are objects (like in C# and probably many other object oriented languages). So, you must create/initialize them using the new keyword.

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.