Dfrtbx
Dfrtbx

Reputation: 135

Trouble finding solution to "variable might not have been initialized" error

My java program takes input from the user on the command line. The user has a choice: he may either specify a plain-text file as input with the -inputfile option, or he may leave this option unspecified, in which case the program takes input from System.in. (I've observed this behavior in some programs that come pre-installed with my Ubuntu distro, so I infer that it is acceptable practice.)

So I make a BufferedReader (inBR)that reads from the file, if provided, and a Scanner (inScanner) that reads from System.in otherwise. Only one of these objects is actually instantiated, the other is left as null. Later on, when the program reads a line from input, I have the following code:

String line;
if (inBR != null) {
    line = inBR.readLine(); (1)
} else {
    line = inScanner.nextLine(); (2)
}

Which gives me the compile time errors variable inBR might not have been initialized and variable inScanner might not have been initialized at lines (1) and (2), respectively.

What is the acceptable solution here? I've considered, "initialize the variable that's supposed to be null as an Object to shut up the compiler." But this is just a hack; surely there's a better way.

Also, why isn't this a runtime exception, as a NullPointerException?

EDIT: inScanner.readLine() => inScanner.nextLine()

Upvotes: 1

Views: 286

Answers (3)

user2122031
user2122031

Reputation: 601

In java all variables that are used must be initialized at some point.

public void example(){
  String name;

  if(name == null) return null;

}

In the above example the variable name has not been initialized. There are several ways to solve this problem:

public void example1(){
  String name = null;

  if(name == null) return null;
}

This would solve the problem.

This would also solve the problem

public void exapmle2(){
  String name = "";

  if(name == null) return null;

}

Upvotes: 1

user3688447
user3688447

Reputation: 15

Make the condition whether or not a file is provided. For example, if a file is provided, create the buffered reader and set line immediately. Otherwise, create a scanner and set the line.

Upvotes: 0

Eran
Eran

Reputation: 394146

Declaring them this way would avoid the compilation error :

BufferedReader inBR = null;
Scanner inScanner = null;

Of course you still have to give them actual values before accessing them, or you'll get NullPointerException.

Upvotes: 4

Related Questions