Share this page 

Easy keyboard input (JDK1.5)Tag(s): IO


import java.util.Scanner;

class TestScanner {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println(sc.nextLine());
    System.out.println("Done");
  }
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
import java.util.Scanner;

class TestScanner {
  public static void main(String args[]) {
    // if input is
    //    10,12
    // then the output is
    // 10
    // 12
    //
    // we use a regex as delimiter to combine "," and
    // whitespace (in this case the ENTER key)
    Scanner sc = new Scanner(System.in).useDelimiter("[,\\s]");
    while (sc.hasNextInt()) {
      int i = sc.nextInt();
      System.out.println(i);
    }
    System.out.println("Done");
  }
}
Scanner can be used with String or Stream. For exemple, the above HowTo can be written like this :
import java.util.Scanner;

class TestScanner {
  public static void main(String args[]) {
	String input = "10,12"
    Scanner sc = new Scanner(System.in).useDelimiter(",");
    while (sc.hasNextInt()) {
      int i = sc.nextInt();
      System.out.println(i);
    }
    System.out.println("Done");
  }
}