Programming Tips - Java: How to use java.util.Scanner

Date: 2014apr1 Update: 2025oct8 Language: Java Keywords: token, tokenize Q. Java: How to use java.util.Scanner A. Scanner can read a File, String or many other input. It knows about common Java types like floats etc.
// Here is a full example: // (Its "full" in that it compiles but doesn't demo all capabilities) import java.util.Scanner; class Demo { public static final void main(String[] args) { final String sentence = "Good morning, to you"; System.out.println("sentence=" + sentence ); Scanner scan = new Scanner(sentence); while (scan.hasNext()) { String word = scan.next(); System.out.println("word=" + word); } } }
Output:
sentence=Good morning, to you word=Good word=morning, // Notice the comma is included word=to word=you