I'm trying to enter integer value through System.in.read(). But when I'm reading the value it is giving different output 49 for 1, 50 for 2 & so on
int e=(int)System.in.read(); System.out.print("\n"+e);
-
The reason for that is that the `System.in.read()` reads a character, not an integer. So when you cast the char '1' to an int, you get the ASCII value of the char '1', which is 49. – Dimitar Spasovski Jun 10 '18 at 21:03
-
https://stackoverflow.com/q/15273449/4472840 – Yosef Weiner Jun 10 '18 at 21:08
3 Answers
Because character 1
(i.e. char ch = '1'
) has ASCII code 49
(i.e. int code = '1'
is 49
).
System.out.println((int)'1'); // 49
To fix your examle, just substract code for 0
:
int e = System.in.read() - '0';
System.out.println(e); // 1
![](../../users/profiles/3461397.webp)
- 12,764
- 2
- 17
- 25
-
-
1@Andreas I agree, `Scanner` is much better, but this is not a scope of this question. – oleg.cherednik Jun 10 '18 at 21:40
You're reading char with function
System.in.read()
You can see the use of System.in.read() here. Also please check here how to read a value from user.
![](../../users/profiles/9664820.webp)
- 636
- 1
- 6
- 19
-
1No *"cast to int"*, since [`read()`](https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html#read--) returns an `int`. – Andreas Jun 10 '18 at 21:19
-
As other answers have mentioned, System.in.read()
reads in a single character in the form of an int
, or -1
if there is no input to read in. This means that characters read in with System.in.read()
will be int
s representing ASCII values of the read characters.
To read in an integer from System.in
it might be easier to use a Scanner
:
Scanner s = new Scanner(System.in);
int e = s.nextInt();
System.out.print("\n"+e);
s.close();
or, if you wish to stick to using System.in.read()
, you can use Integer.parseInt(String)
to obtain an integer off of the character input from System.in.read()
:
int e = Integer.parseInt("" + (char) System.in.read());
System.out.print("\n"+e);
Integer.parseInt(String)
will throw a NumberFormatException
you can catch if the input is not a number.
![](../../users/profiles/5921170.webp)
- 845
- 1
- 10
- 26