-1

I started creating a Hangman game. I want to have a main class, and a method class. I want to get a secret word, but I get an error:

non-static method getWord() cannot be referenced from a static context.

Maybe I get this error because no object has been created? What's wrong here and how do I fix this?

PS: maybe implementing it with enum could be better, but I want to start this way.

public class HangmanMain {
    public static void main(String[] args) {
        String secretWord; /* chosen secret word*/
        secretWord = HangmanUtil.getWord();
        System.out.println("");
    }

}

public class HangmanUtil {

    private String[] wordBank = {"pool","ice", "america", "hook", "book", "glass" , "hint", "giraffe"," elephant", "ocean","market"};

    String guess;
    private int bodyPartsLeft;

    String getWord(){
        int len = wordBank.length;
        int rand = (int)(Math.random() * (len + 1));
        return wordBank[rand];
    }

}  
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Niminim
  • 668
  • 1
  • 7
  • 16
  • "Maybe I get this error because no object has been created ?" - That's exactly right. You need to instantiate the containing class before you can call one of its non-static methods. – JonK Oct 16 '15 at 14:14

2 Answers2

0

You answered yourself :

Maybe I get this error because no object has been created ?

Either create a new instance of HangmanUtil or make the HangmanUtil.getWord() method static.

EDIT : considering it's a utility class, I believe second option is better : make HangmanUtil a static class with static methods.

Gaël J
  • 11,274
  • 4
  • 17
  • 32
  • Thanks:). "private static String[] wordBank =...," and "static String getWord(){..." solve the problem (and also create a new instance). "public static class HangmanUtil {" doesn't compile. – Niminim Oct 16 '15 at 14:29
  • Yes, a class cannot be marked as `static`, only its content. You whould also make the constructor `private` to fully make the class "static". – Gaël J Oct 16 '15 at 14:31
0

You can't call a method via ClassName.methodName() unless the method is static.

If you want to call a non-static method, you need an instance. E.g.

HangmanUtil hu = new HangmanUtil();
secretWord = hu.getWord();

If you don't want to make an instance, then your method needs to be be marked static, and any other methods or fields it references must also be static.

khelwood
  • 55,782
  • 14
  • 81
  • 108