Results 1 to 4 of 4
  1. #1
    Adithi is offline Member
    Join Date
    Aug 2011
    Posts
    14
    Rep Power
    0

    Default System.in.read()

    Please look at my program:

    import java.io.*;
    class SysIn{
    public static void main(String args[]){
    int ch=0;
    System.out.println("Enter value");

    try{
    ch=System.in.read();
    System.out.println("Value entered:"+ch);
    }
    catch(IOException io){
    System.out.println("Error from user");
    }
    }
    }
    -----------------------
    Output:
    Enter value: 123
    Value Entered:49
    -----------------------------
    Why does it display 49 when i give 123. Do I need to do any type casting in this program... please somebody advise.
    Thankyou.

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,299
    Blog Entries
    7
    Rep Power
    24

    Default

    System.in.read() reads just one byte from the InputStream. When you typed the three characters "123" it read the first character (as a byte). 49 is the Unicode point value for the character '1'. Read the API documentation for the Scanner class and other Reader classes.

    kind regards,

    Jos
    The only person who got everything done by Friday was Robinson Crusoe.

  3. #3
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,029
    Rep Power
    29

    Default

    When you read data from the keyboard using a low level method, the value you read is the keyboard character's value. Often spoken of as ASCII values.
    For example the character '4' has a value of 52. The character '1' has a value of 49.
    If you want to see the char value, make ch type char or cast it to char when you print it: (char)ch

    Try this to see:
    System.out.println("as char " + (char)49);

  4. #4
    Adithi is offline Member
    Join Date
    Aug 2011
    Posts
    14
    Rep Power
    0

Similar Threads

  1. system.out.printf versus system.out.format
    By bigsonny in forum New To Java
    Replies: 10
    Last Post: 06-21-2011, 10:40 PM
  2. Replies: 8
    Last Post: 06-21-2011, 02:21 PM
  3. How to read xml file located in local system using Java
    By java_kick in forum Advanced Java
    Replies: 2
    Last Post: 04-06-2009, 11:28 PM
  4. System.in.read() confusion
    By ankurdh in forum New To Java
    Replies: 5
    Last Post: 01-08-2009, 09:28 AM
  5. System.in.read(); strange error!
    By kantze in forum New To Java
    Replies: 2
    Last Post: 03-19-2008, 02:44 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •