Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

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

char n = (char)bufferRead.read();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top