Read an int from Standard Input in Java

Description

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

Example


//  w  ww . j  av a2  s . c om
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
  public static void main(String[] ap) {
    String line = null;
    int val = 0;
    try {
      BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
      line = is.readLine();
      val = Integer.parseInt(line);
    } catch (NumberFormatException ex) {
      System.err.println("Not a valid number: " + line);
    } catch (IOException e) {
      System.err.println("Unexpected IO ERROR: " + e);
    }
    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