Scanners
by
, January 29th, 2012 at 04:55 PM (1521 Views)
I forgot to write about the scanner, so I'm going to do that now.
Basically, a scanner is used to get information from the user. At this stage, the scanner will be used only to gather information from the keyboard. Here's how it works.
Firstly, we must import the scanner, since it's not available in the default library. It's found in the java.util library, so we write import java.util.Scanner; at the top of our code to allow us to use the scanner. Capitalisation here is important.
Next, we need to create a new scanner variable to let us use the scanner. Do this by typing Scanner followed by the name of the object (in this case, I called mine input). Set the object equal to new Scanner with the parameter of System.in - this allows us to read the keyboard input.
Now whenever you type into the console (or other field), the text you enter before pressing enter will be stored in the input scanner variable. To output this, we need to figure out what data type we're working with. In this case, it's a string of text so we use input.nextLine(). That's really all there is to it!