Read an int from Standard Input with Scanner in Java

Description

The following code shows how to read an int from Standard Input with Scanner.

Example


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

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip