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.

有帮助吗?

解决方案

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

其他提示

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();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top