3 Replies - 235 Views - Last Post: 29 December 2012 - 07:58 AM Rate Topic: -----

#1 dulvinrivindu  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 51
  • Joined: 25-September 12

A problem in system.in.read

Posted 28 December 2012 - 11:50 PM

public static void main(String args[]){
		int x=1 ;
		try{
			x=(int) System.in.read();
		}
		catch(Exception e){}
		System.out.println(x);
	}


When I input "1" the output is 49. I cant understand why
Is This A Good Question/Topic? 0
  • +

Replies To: A problem in system.in.read

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10186
  • View blog
  • Posts: 37,603
  • Joined: 27-December 08

Re: A problem in system.in.read

Posted 28 December 2012 - 11:59 PM

*
POPULAR

System.in.read() treats your input as a char. You might be better off using something like a Scanner instead of System.in.read(), though. It's more flexible.
Was This Post Helpful? 5
  • +
  • -

#3 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 1907
  • View blog
  • Posts: 3,953
  • Joined: 11-December 07

Re: A problem in system.in.read

Posted 29 December 2012 - 05:48 AM

Just to clarify, 49 is the unicode value for the character "1". Each character has its own number and that's whet you are seeing when you read an int from System.in.

For what it's worth, I've never used System.in.read() directly in over 10 years of programming Java. Macos's suggestion of using a Scanner is worth considering. BufferedReader is another option but that's a bit old fashioned these days.
Was This Post Helpful? 4
  • +
  • -

#4 dulvinrivindu  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 51
  • Joined: 25-September 12

Re: A problem in system.in.read

Posted 29 December 2012 - 07:58 AM

Thanks guys. I found some articles about scanner. I got through. :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1