Prefer using a buffered input stream reader to a scanner for user input for the following reasons:
- Buffered readers are synchronized. Scanner is not synchronized for scanning. (It is only for character skipping, marking and resetting though by default.) That means that Scanner is fine for a stream that will only be accessed from one location, typically one that is encapsulated in a single method in a single thread, such as when a database is being loaded. However, synchronization is recommended for when you have a stream that can be access from multiple places. This is the case with System.in which is the standard input stream, accessible from many places.
- You can set a buffered reader's character buffer. A scanner's character buffer is always 1 024 characters, never bigger or smaller. You know for your self what the best size for your character buffer is.
- It's a good habit to get into. Being aware of synchronization policies is a good idea. Synchronization can have a higher cost than no synchronization, but it's worth it if an object is being accessed from many possible places. You're more likely to be using the stream interface rather than the scanner interface, so it's a good idea to use both. Streams seem to be more difficult for beginnings, so it's a good idea to get more practice with them. Scanners are easy.
The only real caveat is that it involves checked exceptions. How you handle this depends on the situation, but usually propagating it to a method that can handle it is the right thing to do. (If you know for certain that an exception can never be thrown, you can wrap it in a catch construction, but that's another topic. You can email me for more info on that.) It's a little more work, but it's worth it for the aforementioned pros :)
If you really want to, you can wrap a buffered input stream reader in a scanner, but you won't get the benefit of setting the buffer size. It should probably be 1 024 as is the scanner.
Example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
public final class UserInputExample
{
public static void main(final String... args) throws IOException
{
// World's longest name is 746 letters long, plus 3 characters for age, plus a little extra room. This is probably an extreme case.
final BufferedReader in = new BufferedReader(new InputStreamReader(System.in), 800);
final PrintStream out = System.out;
out.print("Please enter your name: ");
final String name = in.readLine();
out.println();
out.println(new StringBuilder()
.append("Hello, ")
.append(name).append('!')
);
out.print("How old are you? ");
final int age = Integer.parseInt(in.readLine());
out.println();
out.println(new StringBuilder()
.append(name).append(" is ")
.append(age).append(" years old.")
);
}
private UserInputExample() {}
}