2

I just did USACO/Number Triangles ex and found a problem about read file.I used "Scanner" to read in the file first, but test 9 was failed, because the running time was 1.8secs, which exceeded the limitation 1.3secs.Then, I used "StreamTokenizer" to read in the file, finally all tests were cleared. At this time, test 9 only took 0.38secs. I do not know why there was such big difference between "Scanner" and "StreamTokenizer".

"Scanner" code:

    Scanner sc = new Scanner(new FileReader("numtri.in"));
    int n= sc.nextInt();
    int Array[][] = new int[n][n];
    for(int i=0;i<n;i++){
         for(int j=0;j<=i;j++){
               Array[i][j]=sc.nextInt();
         }
    }

"StreamTokenizer" code:

StreamTokenizer sc = new StreamTokenizer(new BufferedReader(new FileReader("numtri.in")));

int nextInt() throws IOException
   {
      sc.nextToken();
      return (int)sc.nval;
   }

int n = nextInt();
int Array[][] = new int[n][n];
for(int i=0;i<n;i++){
    for(int j=0;j<=i;j++){
        Array[i][j]=nextInt();
    }
 }
Nicki
  • 21
  • 1
  • possible duplicate of [Scanner vs. StringTokenizer vs. String.Split](http://stackoverflow.com/questions/691184/scanner-vs-stringtokenizer-vs-string-split) – mkazma Jul 23 '14 at 08:27
  • It would be nice to know what test 9 is. By the way have you considered Files.newBufferedReader() available in Java 7? You can find more info on reading files at http://docs.oracle.com/javase/tutorial/essential/io/file.html. – Boris Jul 23 '14 at 08:28
  • 2
    use google, before posting an question. – Deepanshu J bedi Jul 23 '14 at 08:28

0 Answers0