AkshaiShah
AkshaiShah

Reputation: 5939

java - cannot find symbol

If i have this in my main method: PrintWriter output = new PrintWriter(new FileWriter(args[1]));

and this in another method: output.println(currentLine);

and import java.io.*; obviously,

does anyone know why I am getting

cannot find symbol
symbol  : variable output
location: class TestClass
        output.println(currentLine);

Upvotes: 2

Views: 5448

Answers (1)

Attila
Attila

Reputation: 28762

The compiler tells you that the name (symbol) output is not defined in the scope (and enclosing scopes) where you want to use it. Based on the definition

PrintWriter output = new PrintWriter(new FileWriter(args[1]));

it seems you define output in the main() function, but want to use it in a class TestClass, which is not valid as output is only defined within main()

Assuming main() is defined within TestClass you could define output in the class, then assign its value in main() and use it within the class later:

public class TestClass {
  PrintWriter output;
  public void write(String currentLine) {
    output.println(currentLine);
  }

  public static void main(String[] args) {
    TestClass tc = new TestClass();
    tc.output = new PrintWriter(new FileWriter(args[1]));
    tc.write("Sometext");
  }
}

Upvotes: 2

Related Questions