"Amigo, your time has come. I'm now going to tell you about keyboard input."
"We've used System.out to display data on the screen. To receive input, we'll use System.in."
"But System.in has one shortcoming – it only lets us read character codes from the keyboard. To get around this problem and read big chunks of data all at once, we'll use a more complex construct:"
Input a string and number from the keyboard
InputStream inputStream = System.in; Reader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String name = bufferedReader.readLine(); //Read a string from the keyboard String sAge = bufferedReader.readLine(); //Read a string from the keyboard int nAge = Integer.parseInt(sAge); //Convert the string to a number.
A more compact version of the previous example:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String name = reader.readLine(); String sAge = reader.readLine(); int nAge = Integer.parseInt(sAge);
Even more compact
Scanner scanner = new Scanner(System.in); String name = scanner.nextLine(); int age = scanner.nextInt();
"Uh...I didn't understand anything."
"To read a string from the keyboard, it's most convenient to use a BufferedReader object. But to do that you have to pass in the object you're going to read data from. In this case, System.in."
"But System.in and BufferedReader are incompatible, so we use another adapter – another InputStreamReader object."
"I think I get it now. What is this Scanner class?"
"Scanner can be convenient, but it's not very useful. The thing is, as you proceed (both in studying and working), you'll use BufferedReader and InputStreamReader often, but Scanner – very rarely. It's convenient in our example, but in the future it won't be useful very often. So we won't use it much."
"That seems clear, but I'm not sure I understood everything."