Roman
Roman

Reputation: 131278

Why a "private static" is not seen in a method?

I have a class with the following declaration of the fields:

public class Game {
private static String outputFileName;
....
}

I set the value of the outputFileName in the main method of the class.

I also have a write method in the class which use the outputFileName. I always call write after main sets value for outputFileName. But write still does not see the value of the outputFileName. It say that it's equal to null.

Could anybody, pleas, tell me what I am doing wrong?

ADDED As it is requested I post more code:

In the main:

    String outputFileName = userName + "_" + year + "_" + month + "_" + day + "_" + hour + "_" + minute + "_" + second + "_" + millis + ".txt"; 
    f=new File(outputFileName);
        if(!f.exists()){
        try {
            f.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }               
    System.out.println("IN THE MAIN!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    System.out.println("------>" + outputFileName + "<------");

This line outputs me the name of the file.

Than in the write I have:

public static void write(String output) {
    // Open a file for appending.
    System.out.println("==========>" + outputFileName + "<============");
        ......
}

And it outputs null.

Upvotes: 0

Views: 227

Answers (2)

chris
chris

Reputation: 10003

on the first line of your main code

String outputFileName = ...

needs to be

outputFileName = ...

otherwise you're making a new, local, var called outputFileName, and the private static one isn't getting touched.

Upvotes: 3

Catalin DICU
Catalin DICU

Reputation: 4638

Seems like you have a local variable or a parameter with the same name

Upvotes: 3

Related Questions