1

I have a console menu that has to read inputs a few times in different methods. I use a new BufferedReader(new InputStreamReader(System.in)) to do that. But if this reader is closed in a method it's not useable/openable again because of System.in.

To solve this problem one possibility is to static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); so it's usable several times in different methods with Main.br.readLine();.

Is this a good way or are there much better methods?

cmtjk
  • 359
  • 2
  • 12

1 Answers1

2

Pass the BufferedReader into your method(s) (or make it a shared field), that way you don't have to re-create it. Also, you are correct that closing System.in (or something wrapping System.in) will cause you issues. Instead of

public void foo()

something like

public void foo(BufferedReader reader)
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • So a `static BufferedReader...` or passing it around is a legal way and is both recommended? – cmtjk May 11 '15 at 12:18
  • 1
    `static` would make it a class level field.... it might be an instance field. Of course both are legal. As for recommended, I would prefer making it an argument (Java is pass by value, but the value of an `Object` instance is a reference). – Elliott Frisch May 11 '15 at 12:19
  • Thank you very much! I will pass it to the methods which need it. That seems a good way. – cmtjk May 11 '15 at 12:22