Java I/O How to - Read an int from Standard Input with Scanner


We would like to know how to read an int from Standard Input with Scanner.


/* w  w  w  .  j a v a2  s  .c  o  m*/
import java.util.Scanner;
public class Main {
  public static void main(String[] ap) {
    int val;
    try {
      Scanner sc = new Scanner(;      // Requires J2SE 1.5
      val = sc.nextInt();
    } catch (NumberFormatException ex) {
      System.err.println("Not a valid number: " + ex);
    System.out.println("I read this number: " + val);

The code above generates the following result.