Read N Characters Given Read4 question on clean code hanbook


  • -2
    Z

    public class Solution extends Reader4 {

    public int read(char[] buf, int n) {
    char[] buffer = new char[4];
    int readBytes = 0;
    boolean eof = false;
    while (!eof && readBytes < n) {
    int sz = read4(buffer);
    if (sz < 4) eof = true;
    int bytes = Math.min(n - readBytes, sz); System.arraycopy(buffer /* src /, 0 / srcPos /,
    buf /
    dest /, readBytes / destPos /, bytes / length */);
    readBytes += bytes;
    }
    return readBytes;
    }
    }

    Above is the answer in the handbook.
    I was confused why there is a "if (sz < 4) eof = true;" Cause I though the sz should always be 4, cause buffer is set as 4, and no such moves can down the buffer. And I dont even know why they use the arraycopy, I thought the buffer was always a empty array with 4 NULL. Was that right? Who can help me with this. thanks a lot.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.