Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Shafeeq Ahmed
6,058 PointsUser Input
I have learned two methods to take user input (as String) in java.
method 1
BufferedReader br = new BufferedReader(new FileStreamReader(System.in)); String something = br.readLine();
method 2
Console console = System.console(); String something = console.readLine();
What is the different between these two methods and why should someone choose one over the other?
1 Answer
Rob Bridges
Full Stack JavaScript Techdegree Graduate 35,467 PointsHello!
Console if I remember right was very buggy in IDE's about a year ago, you couldn't even instantiate one without having to do a clever work-around (it would always come out to be null). Granted, I have no tried it recently but personally there are two that you should possibly look at. One is the buffered reader like you mentioned, however the other is the Scanner
This is just my opinion but I dived more head first with Buffered Reader as it required me to put what I've learned into practice quicker (it throws an exception that you have to catch, and other things that make it a bit more difficult to start to use than Scanner did).
The reasons I liked Buffered Reader is once you get into it you can change your buffered reader into a file reader, input reader, and any type of reader that is needed.
To give you some pros of cons of both. The Scanner can parse a string into tokens (which is handy for regular expression, you'll see a bit of this in the next projects!) so Scanner is preferred if using RegEx.
However it's not nearly as synchronized So let's say you have a program with multiple threads (multipe things happening at once) Scanner is actually at a disadvantage here because you have to be careful to not call it when it's already working as this can cause lost input or crashing of your program, where as Buffered Reader would be smart enough to know to wait until it was done before asking again.
Essentially, it's good to have a handle of both, in case come across one of the examples above where one is better than the other. Try them both, after working with them use the one that you like and feel more comfortable with. It really is user preference, just be ready to switch if you come across a case where your natural choice is at a disadvantage.