Skip to content

Reading Input

Scanner Class

The Scanner class is defined in the java.util.Scanner package. The scanner is utilised to read data from an input, within it’s parameters that input location can be defined.

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);
/*
Here we are creating a new Scanner instance and defining System.in (terminal window) as the input location.
'System.in' is a field of the System class representing standard input (usually the console).
*/
System.out.print("Please Enter your age:");
// notice no ln to provide an inline print function
byte age = scanner.nextByte();
System.out.println("You are " + age); //Implicit casting of age from byte to string
/*
The above execution will await user input and return a string
he application prompts and the user can type in an input
let's imply 20 has been typed in
System out will return "You are 20" to console
If the user types in 20.1 an exception will occur as the method cannot implicitly cast mismatched types
For an explicit cast of floats we would call nextFloat or next Double
*/
/*
Lets try to read a string
the Scanner class does not have a nextString method we have next and nextLine
*/
System.out.print("Please Enter your Name:"); // notice no ln to provide an inline print function
String name = scanner.next();
System.out.println("You are " + name);
/*
Let's say the user Typed in John
"You are John" would return
If the user types in "John Doe"
Only "You are John" would return
Each input seperated by a space is known as a token in the next method, therefore for each input we would need to call the next method.
*/
String name = scanner.nextLine();
/*
The nextLine method takes all input tokens on that line and returns accordingly.
This method will also return odd formatting inputs as an example
" John Smith"
Would return the spaces prefixed to the input
*/
String name = scanner.nextLine().trim();
/*
The trim method chained would remove the white spaces.
" John Smith" would now return "You are John Smith"
*/