Search code examples
javastdin

StdIn.readAll() vs. readString()


I was writing code to read string from a file. While using String s = StdIn.readAll(); it worked fine. But I don't understand why, by using

while (!StdIn.readString().isEmpty())
    s = s.concat(StdIn.readString());

I got an java.util.NoSuchElementException error. Is it because the string is too long?

(I was using this Stdln library)

Thank you!


Solution

  • Each of the calls to StdIn.readString() reads another string. So, even if the string you read in the while condition isn't empty, you read (or try to read) another string inside the loop.

    Store in a variable:

    String r;
    while (!(r = StdIn.readString()).isEmpty()) {
      s = s.concat(r);
    }
    

    Incidentally, a better approach than concat would just be to use s += r, or a StringBuilder:

    StringBuilder sb = new StringBuilder();
    String r;
    while (!(r = StdIn.readString()).isEmpty()) {
      sb.append(r);
    }
    s = sb.toString();