Improved ReadLine

Write here if you have problems with your Java source code

Moderator: Board moderators

Post Reply
jdalbey
New poster
Posts: 3
Joined: Thu Dec 10, 2009 6:05 pm

Improved ReadLine

Post by jdalbey »

The sample ReadLn() method doesn't really read an entire line of data. It just reads the number of bytes specified in the parameter. Here is an improved version that actually reads an entire line.

Code: Select all

    /** Return a line of input from System.in,
     *  or null if EOF.
     */
    static String ReadLn () 
    {
        int inbyte = -1;
        StringBuffer line = new StringBuffer();
    
        try
        {
            inbyte = System.in.read();
            while ((inbyte >= 0) && (inbyte != '\n'))
            {
                line.append((char) inbyte);
                inbyte = System.in.read();
            }
        }
        catch (IOException e)
        {
            return (null);
        }

        if ((inbyte < 0) && (line.length() == 0)) return (null);  // eof
        return line.toString();
    }
Post Reply

Return to “Java”