1

I am trying to run a simple code, in which the first few lines are

     **System.out.println("Enter the number of nodes\n");
     BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
     int n = bufferRead.read();
     System.out.println(n);**

This part of the code is in between the try-catch pair. I just have to display the number of nodes, but instead of displaying the value of n, it displays the values preceeding 48. For example, if the input for n is 1, the output should be "1", but it displays "48". If the input is 2, it displays 49 and so on.

Please assist me with this and enlighten me with your knowledge. Thanks.

Ellipsis
  • 19
  • 1
  • 1
  • 6

3 Answers3

1

It's displaying ASCII value of the number you get (you are reading a char and then casting it to int). You should read numbers using

Scanner scanner = new Scanner(System.in); 
int n = scanner.nextInt();

Take a look to the Scanner class that is very helpful in these cases: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

Averroes
  • 4,168
  • 6
  • 50
  • 63
  • Thanks for the help.. really appreciate it.. I understood where I went wrong.. Í can simply use Scanner to read an integer rather than BufferedReader.. I complicated things :) – Ellipsis May 31 '13 at 08:49
1

48 is the ASCII code for 1... so you can display n-'0' to "convert" ascii numbers to real number

Guest
  • 26
  • 1
  • Thanks a lot. Appreciate your help. I can simply use scanner to display int, rather than using Bufferedreader :) – Ellipsis May 31 '13 at 08:50
1

its display ascii value cast it to a char if you want to print char itself

char n = (char)bufferRead.read();
someone
  • 6,577
  • 7
  • 37
  • 60