0
public static void main(String[] args) throws Exception {
    BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
    int a = inp.read();
    System.out.println(a);
    inp.close();
}

Console:

10 but it outputs 49 as result

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
jallaad7
  • 3
  • 5

3 Answers3

1

Use it as :

Integer.parseInt(br.readLine());

BufferedReader#read reads single character[0 to 65535 (0x00-0xffff)] from the stream, so it is not possible to read single integer from stream.

An InputStreamReader needs to be specified in the constructor for the BufferedReader. The InputStreamReader turns the byte streams to character streams

You can check scanner-vs-bufferedreader

Community
  • 1
  • 1
Umais Gillani
  • 608
  • 4
  • 9
0

Because 49 is the Unicode value for the character '1'. read returns a single character (as an int, so it can use -1 to signal end-of-stream).

Options:

  • If you want to read an entire line of text, use readLine to read a string.

  • If you want to output the character you read, after checking that it's not -1 (which means you've reached the end of the stream), cast it to char:

    if (a != -1) {
        char ch = (char)a;
        System.out.println(ch); // will output 1
    }
    

    If you want to read all the characters, you'll need a loop.

  • If you want to read an integer, you may want Scanner.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0
BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
    String a = inp.readLine();
    System.out.println(a);
    inp.close();

read reads only single character and returns ascii value. Use readLine() to read full line and convert it into Integer.

Kranthi
  • 11
  • 2
  • Not ASCII, UTF-16: [The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached](http://docs.oracle.com/javase/8/docs/api/java/io/Reader.html#read--). Many, many mentions of ASCII are erroneous. – Tom Blodget Nov 14 '16 at 18:43