Results 1 to 4 of 4
  1. #1
    blessed07 is offline Member
    Join Date
    Jan 2010
    Posts
    7
    Rep Power
    0

    Smile char and throws java.io.IOException

    Hi.
    Is throws java.io.IOException can be used together with char only?
    How about int, String, long... ...
    for example,

    class ReadChar {
    public static void print( long num )
    throws java.io.IOException{

    System.out.println( "Type a number and press [Enter]" );
    num = (long)System.in.read();
    System.out.println( "You typed " + num );
    }
    }

    In this case, when I type 7, it stated I typed 55.
    Why? Hope to get the answer soon.
    Thank you.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    This has nothing to do with IOException and all to do with wrong code. You don't read in input this way. System.in is an InputStream and calling read() reads a byte from the Stream as a byte, not as a character in a String.

    Instead you should use either a BufferedInputStream:
    Java Code:
     BufferedReader in
       = new BufferedReader(new InputStreamReader(System.in));
    or a Scanner object:
    Java Code:
     Scanner scan = new Scanner(System.in);

  3. #3
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Just an FYI - It said you typed 55 because you did. In Ascii. The character for the number 7 is at index 55 on the ASCII Chart. Do what fubarable said and you shouldn't have this problem.

  4. #4
    blessed07 is offline Member
    Join Date
    Jan 2010
    Posts
    7
    Rep Power
    0

Similar Threads

  1. java.io.IOException: Premature EOF
    By CrazyVag in forum New To Java
    Replies: 5
    Last Post: 01-26-2010, 10:55 PM
  2. Calling on class with throws IOException
    By gisler in forum Networking
    Replies: 5
    Last Post: 12-01-2009, 04:20 PM
  3. Replies: 1
    Last Post: 11-25-2009, 06:48 AM
  4. change throws IOException
    By manhtungtnk28@gmail.com in forum New To Java
    Replies: 7
    Last Post: 11-23-2009, 08:39 AM
  5. Replies: 4
    Last Post: 06-24-2009, 06:34 AM

Posting Permissions

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