Results 1 to 3 of 3
  1. #1
    kantze is offline Member
    Join Date
    Mar 2008
    Posts
    1
    Rep Power
    0

    Default System.in.read(); strange error!

    Hi, i'm new to java. I'm trying to read an integer and to print it.

    Here is what i've done so far...
    Java Code:
    import java.io.IOException;
    
    public class helloworld {
    
    	public static void main(String[] args) throws IOException {
    		int a = System.in.read();
           System.out.println(a);
    }
    }
    The problem is, that if for example i write 3 the console prints 51 ( its' ansi representation, i guess??)

    I must write this
    Java Code:
     System.out.println( (char)a);
    to make it work.

    But, when I do this
    Java Code:
    import java.io.IOException;
    
    public class helloworld {
    
    	public static void main(String[] args) throws IOException {
    		int a = 3;
           System.out.println(a);
    }
    }
    everything is printed right.

    Could anyone tell me what's happening??

  2. #2
    Rajesh is offline Member
    Join Date
    Mar 2008
    Posts
    3
    Rep Power
    0

    Default

    System.in.read() method reads the next byte of data from inputstream. The Value byte is returned as an int in the range 0 to 255. If no byte is available the value -1 is returned.

    But in the code fragment int a=3; we are assinging integer value to position allocated for integer variable a. So it creates no problem.

    hope is usefull,
    thank you

  3. #3
    Rajesh is offline Member
    Join Date
    Mar 2008
    Posts
    3
    Rep Power
    0

    Default

    Instead you may try with this simple code to read an integer from console


    import java.io.DataInputStream;
    public class demo
    {
    public static void main(String s[])
    {
    int a;
    DataInputStream dis = new DataInputStream(System.in);
    a=Integer.parseInt(dis.readLine());
    System.out.println(a);
    }
    }

Similar Threads

  1. Need help on a strange file access prob
    By squad in forum Advanced Java
    Replies: 0
    Last Post: 03-21-2008, 10:55 AM
  2. How to read the following
    By rrp in forum New To Java
    Replies: 0
    Last Post: 12-03-2007, 06:16 PM
  3. Strange error message "Source not found"
    By ppayal in forum Eclipse
    Replies: 0
    Last Post: 11-25-2007, 06:19 PM
  4. Replies: 1
    Last Post: 08-07-2007, 07:40 AM
  5. read txt file
    By sureshsri1981 in forum JavaServer Pages (JSP) and JSTL
    Replies: 0
    Last Post: 08-05-2007, 03:49 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
  •