It's not really a problem that I am facing, more like looking for explanation ... I had this

import java.util.*;
import java.io.*;

public class ReadFile {
    private static int lines=0;
    private static List<String> words=new ArrayList<String>();
    private static String fullLine;
    private static int indexOfSpace;
    private static String getWord;
    private static String getHint;

    public static void main(String[] args) {
    File file = new File("C:\\Users\\User\\eclipse\\readFileAllLines\\words.txt"); //Windows path

        try {

            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line+" "+lines);
                words.add(lines,line);
                lines++;
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        fullLine = words.get(0);
        indexOfSpace = fullLine.indexOf(" ");
        System.out.println(indexOfSpace);
        getWord = fullLine.substring(0,indexOfSpace);
        getHint = fullLine.substring(indexOfSpace+1);
        System.out.println("The word is "+getWord + " and the hint is "+getHint);

    }
}

which works great, but notice that I had to declear my list as static to be able to add elements to it(compiler complained if not static)

Then I wanted to merge the code with the logic of my Hangman Game

import java.util.*;
import java.io.*;

class HangmanLogic{
    private String[] words = {"iwin","iwin","iwin","iwin"}; 
    private static String wordToGuess;
    Random rnd = new Random();
    private static String letter;
    private int wrongGuesses = 0;
    private int guessedLetter;
    private ArrayList<String> al = new ArrayList<String>();
    private static Hangman hmGUI = new Hangman();
    public final String newLine = "\n";


    private static int lines=0;
    private List<String> linesInFile=new ArrayList<String>();
    private static String fullLine;
    private static int indexOfSpace;
    private static String getWord;
    private static String getHint;


    HangmanLogic(Hangman hm){
        this.hmGUI = hm;

        File file = new File("C:\\Users\\User\\eclipse\\readFileAllLines\\words.txt"); //Windows path

        try {

            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line+" "+lines);
                linesInFile.add(lines,line);
                lines++;
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
/*
        fullLine = linesInFile.get(0);
        indexOfSpace = fullLine.indexOf(" ");
        System.out.println(indexOfSpace);
        getWord = fullLine.substring(0,indexOfSpace);
        getHint = fullLine.substring(indexOfSpace+1);
        System.out.println("The word is "+getWord + " and the hint is "+getHint);
*/

        wordToGuess = words [rnd.nextInt(words.length)]; // Choose a random word from the list
        for (int i = 0; i<wordToGuess.length();i++){ //create all letters represented by "_"
            al.add(i," _ ");
        }
        printWordSoFar(al);
        hmGUI.updateMessage(newLine);
        System.out.println(al);
        System.out.println(wordToGuess);
    }

    public static void main (String[] args){

    }
    public static String setLetter(String s){
        letter = s;
        return letter;
    }
    public String getLetter(){
        return letter;
    }

    public void tryLetter(String s){
        if(wordToGuess.contains(letter)){ 

                //guessedLetter = wordToGuess.indexOf(letter); //location of the guessed letter
                //al.set(guessedLetter,letter); //replace the "_" with the letter guessed
                //printWordSoFar(al);
                /* The code up is for single occurance of string, below for multiple*/
                String aLetter;
                for (int i=0; i<wordToGuess.length();i++){

                    aLetter = wordToGuess.substring(i,i+1);
                    if(letter.equals(aLetter)) al.set(i,letter);
                }
                printWordSoFar(al);

            if(!al.contains(" _ ")) { // word completed
                hmGUI.updateMessage("Congratulations, you won!");
                hmGUI.turnOffLetter();
            }
        }
        else {
            wrongGuesses++;
            hmGUI.updateMessage("Wrong, try again!"+ wrongGuesses + "Out of 5 wrong attempts."+newLine);
            hmGUI.setPicture(hmGUI.getIcon(hmGUI.getAl(),wrongGuesses));
            if(wrongGuesses>=5) {
                hmGUI.updateMessage("Game over, you Lost!"+newLine);
                hmGUI.turnOffLetter();
            }
        }
    }
    public void printWordSoFar(ArrayList<String> al){
        for (String s : al){
            hmGUI.updateMessage(s);
        }
        hmGUI.updateMessage(newLine);
    }
    public int getWrongGuesses(){
        return wrongGuesses;
    }
}

Sorry for messy code, just added it and faced the problem, from my previous file list was static, when I added it here the compiler gives errors as follows:

C:\Users\User\eclipse\Hangman>java HangmanLogic
word1 hint1 0
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
        at HangmanLogic.<init>(HangmanLogic.java:37)
        at Hangman.<init>(Hangman.java:15)
        at HangmanLogic.<clinit>(HangmanLogic.java:12)

Notice it read the first line of the file and then gave an error
This was pointing at the line where I add elements to my list, as an instinct I just removed "static" and it worked

C:\Users\User\eclipse\Hangman>java HangmanLogic
word1 hint1 0
word2 hint2 1
word3 hint3 2
word4 hint4 3
word5 hint5 4
[ _ ,  _ ,  _ ,  _ ]
iwin

So, I am confused how did "static" have an influence of writing to the list in a constructor while it was required when I was added elements in main() ?

Recommended Answers

All 3 Replies

A general rule I follow by, is that the only thing needed in main is a call to create a new instance of the class. That way I can keep the class not static and everything else that way too, unless needed.

commented: A good "general rule". +15

So static members are needed in main, and not in other methods? Makes sense in a way that using methods you can set/get them but for main if you want to set something you have to have it static, right?

Static methods execute without an assocated instance of the class, so they don't have any direct access to any instance variables or instance methods. They only have direct access to static variables and static methods. It's nothing to do with get/set as such.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.