0

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);

3 Answers3

2

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
oleg.cherednik
  • 12,764
  • 2
  • 17
  • 25
1

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.

namokarm
  • 636
  • 1
  • 6
  • 19
1

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 ints 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.

Kröw
  • 845
  • 1
  • 10
  • 26