title: An alternative to reading input from Java's System.in
body: <p>I’m working on the UVa Online Judge problem set archive as a way to practice Java, and as a way to practice data structures and algorithms in general.</p>
  
  <p>They give an example input file to submit to the online judge to use as a starting point (it’s the solution to problem 100).  </p>
  
  <p>Input from the standard input stream (java.lang.System.in) is required as part of any solution on this site, but I can’t understand the implementation of reading from System.in they give in their example solution.  It’s true that the input file could consist of any variation of integers, strings, etc, but every solution program requires reading basic lines of text input from System.in, one line at a time.  There has to be a better (simpler and more robust) method of gathering data from the standard input stream in Java than this:</p>
  
  <pre><code>public static String readLn(int maxLg) {
      byte lin[] = new byte[maxLg];
      int lg = 0, car = -1;
      String line = “”;
      try {
          while (lg &lt; maxLg) {
              car = System.in.read();
              if ((car &lt; 0) || (car == ‘\n’)) {
                  break;
              }
              lin[lg++] += car;
          }
      } catch (java.io.IOException e) {
          return (null);
      }
      if  ((car &lt; 0) &amp;&amp; (lg == 0)) {
          return (null); // eof
      }
      return (new String(lin, 0, lg));
  }   
  </code></pre>
  
  <p>I’m really surprised by this.  It looks like something pulled directly from K&amp;R’s “C Programming Language” (a great book regardless), minus the access level modifer and exception handling, etc.  Even though I understand the implementation, it just seems like it was written by a C programmer and bypasses most of Java’s object oriented nature.  Isn’t there a better way to do this, using the StringTokenizer class or maybe using the split method of String or the java.util.regex package instead?</p>