How does scanner work
The scanner method is a useful way to get input in the form of a data type or string. Scanners can be used for manipulating the data held for a particular data type or string.
How to use a scanner
Before we start, we want to add this code to the top of our program…
import java.util.Scanner;
And we want to add this to our main function with a useful name for the Scanner object. It should explain what the scanner does...
public static void main(String[] args){
Scanner input = new Scanner(System.in);
//Scanner 'the name of your scanner' = new Scanner(System.in);
}
Scanner functions
Scanner can be used in many different ways. We usually use a scanner for input from a user, but a scanner can also be used for string manipulation. String manipulation is where we change a string by using the information that we get from said string. This is how we input strings from the user…
public static void main(String[] args){
Scanner userInput = new Scanner(System.in);
//Scanner 'the name of your scanner' = new Scanner(System.in);
System.out.println("Type a Sentence");
String userSentence = userInput.nextLine();
System.out.println("The user said: " + userSentence);
//This will print out: The user said: (whatever they input)
}
Scanner can also detect the next word in a string or only input one word from the user. For example...
public static void main(String[] args){
Scanner userInput = new Scanner(System.in);
//Scanner 'the name of your scanner' = new Scanner(System.in);
System.out.println("Type a Word");
String word = userInput.next();
//the line above will take the next word a user input
System.out.println("The users word was: " + word);
/*This will print out:
The users word was: (the first word the user input)*/
}
We use ‘.nextBoolean()’ instead of ‘.nextLine()’ if we want a boolean input, ‘.nextInt()’ if we want int type input, ‘.nextLong()’ for a long value input, ‘.nextDouble()’ for a double type input, etc.
Scanner userInput = new Scanner(System.in);
//Scanner 'the name of your scanner' = new Scanner(System.in);
System.out.println("Type a number");
int number = userInput.nextInt();
//the line above will take the next number a user inputs
System.out.println("The users number was: " + number);
//this prints: The users number was: (the number they input)
After we are done with using a Scanner we can put this function to make sure it is not used by the user again...
Scanner userInput = new Scanner(System.in);
//Scanner 'the name of your scanner' = new Scanner(System.in);
//we put our input code here
userInput.close();
//we can use this to close the scanner