So you need to accept user input in Java and you heard Scanner is the popular kid in town. Good call. Scanner is simple, standard, and irritatingly specific about newlines. This short guide shows how to import Scanner set it up read different types of input and avoid the common newline trap while keeping things tidy and mildly amusing.
Put the Scanner import near the top of your Java file so the compiler knows what you mean when you type Scanner. A typical line looks like this
import java.util.Scanner
Friendly reminder, when you paste into a real Java file remember to end the import with a semicolon character so the compiler stops complaining.
Instantiate a Scanner that reads from System.in so your program can accept what the user types. Use a clear name so you do not accidentally shadow other classes named Scanner elsewhere.
Scanner scanner = new Scanner(System.in)
If you prefer automatic cleanup use try with resources which closes the Scanner for you when the block ends.
try (Scanner scanner = new Scanner(System.in)) {
// use scanner here
}
Closing a Scanner frees resources and is polite in long running applications. For tiny demo programs you can skip it and nobody will write angry Stack Overflow posts. If your code is a library avoid closing System.in because callers may want it open. Try with resources is a neat compromise for short apps.
Scanner has a handful of convenient methods. Pick the one that matches the data you expect.
nextLine()
reads a whole line including spaces and then returns itnext()
grabs the next token which is good for single wordsnextInt()
reads an integer valuenextDouble()
reads a floating point numbernextInt and nextDouble do not consume the trailing newline after the number. That means a subsequent call to nextLine can return an empty string and you will stare at your screen wondering why your program hates you. Two simple fixes work well.
scanner.nextLine()
to consume the leftover newline before you read the next full linenextLine()
and parse them with Integer.parseInt
or Double.parseDouble
to avoid mixing token and line methodsExample pattern to avoid surprises
int age = scanner.nextInt()
scanner.nextLine() // consume leftover newline
String name = scanner.nextLine()
import java.util.Scanner
at the top of the fileSystem.in
There you go. You can now import Scanner read console input and handle the newline gremlins like a pro. If you want a slightly more robust approach consider reading lines and parsing them which saves you from debugging phantom empty strings at midnight.
I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!
This is a dedicated watch page for a single video.