Long live the Scanner
class, a few examples for self-reference.
1. Read Input
1.1 Read input from the console.
JavaScanner1.java
package com.favtuts.io.console; import java.util.Scanner; public class JavaScannerExamples { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { System.out.print("Please enter your name: "); String input = scanner.nextLine(); System.out.println("name : " + input); System.out.print("Please enter your age: "); int age = scanner.nextInt(); System.out.println("age : " + age); } } }
Output
Please enter your name: favtuts
name : favtuts
Please enter your age: 38
age : 38
For scanner.nextInt()
, if invalid input, it will throws java.util.InputMismatchException
Please enter your name: favtuts
name : favtuts
Please enter your age: 38wsss
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at com.favtuts.io.console.JavaScannerExamples.main(JavaTest.java:15)
2. Split Input
2.1 By default, the Scanner
uses whitespace as delimiters to break its input into tokens.
JavaScanner2.java
package com.favtuts.io.console; import java.util.Scanner; public class JavaScannerExamples { public static void main(String[] args) { // Example 2 String input = "1,2,3,4,5"; try (Scanner s = new Scanner(input).useDelimiter(",")) { while (s.hasNext()) { System.out.println(s.next()); } } } }
Output
1
2
3
4
5
3. Read File
3.1 We also can use Scanner
to read a file.
JavaScanner3.java
package com.favtuts.io.console; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class JavaScannerExamples { public static void main(String[] args) { // Example 3 try (Scanner sc = new Scanner(new File("/home/tvt/workspace/favtuts/pom.xml"))) { while (sc.hasNext()) { System.out.println(sc.nextLine()); } } catch (FileNotFoundException e) { e.printStackTrace(); } } }
Download Source Code
$ git clone https://github.com/favtuts/java-core-tutorials-examples
$ cd java-io/console