FastScanner and PrintWriter as alternatives to Scanner and System.out.println in Java.

Правка en3, от mason_24, 2022-05-30 02:00:03

If you are a Java programmer interesting in Competitive Programmer, you do not have time to learn C++ yet and you are facing some issues reading inputs and writing outputs quickly and safely or your programs usually ran into TLE (Time Limit Exceeded), because of the slowness while reading inputs and writing outputs, I have a quick solution for you from now on.

1) In order to read faster, the basic class Scanner is really slow and it consumes lot of memory. You will need to implement a class like following to enable a faster way to scan inputs from your input stream. Here is the class.

import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FastScanner {
    private BufferedReader reader = null;
    private StringTokenizer tokenizer = null;

    public FastScanner(InputStream in) {
        reader = new BufferedReader(new InputStreamReader(in));
        tokenizer = null;
    }

    public String next() {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }

    public String nextLine() {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                return reader.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return tokenizer.nextToken("\n");
    }

    public long nextLong() {
        return Long.parseLong(next());
    }
     
    public int nextInt() {
        return Integer.parseInt(next());
    }
    
    public double nextDouble() {
    	 return Double.parseDouble(next());
	 }
    
    public int[] nextIntArray(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++)
            a[i] = nextInt();
        return a;
    }
    
    public long[] nextLongArray(int n) {
        long[] a = new long[n];
        for (int i = 0; i < n; i++)
            a[i] = nextLong();
        return a;
    } 
}

2) In order to write outputs, you will need to use the class PrintWriter from the java.io package of the Java libraries. No need to use System.out.println, which is also slow. Here is the details about PrintWriter class.

3) Here is an example of code on how to use it. 3.1) sample input: fast-scanner-test-sample.in

```
12345678901234
This is just a test of the FastScanner class.
```

3.2) sample input: fast-scanner-test-sample.in

12345678901234
This is just a test of the FastScanner class.

3.3) sample code on how to use FastScanner, PrintWriter

import java.io.PrintWriter;

public class FastScannerTest {
 
    public static void main(String[] args) throws Exception {
        FastScanner scanner = new FastScanner(System.in);
        long val = scanner.nextLong();
        String str = scanner.nextLine();
 
        PrintWriter printWriter = new PrintWriter(System.out);
        printWriter.printf("%d\n", val);
        printWriter.printf("%s\n", str);
        printWriter.close();
    }
}

3.4) How to compile

javac FastScanner.java
javac FastScannerTest.java

3.5) How to run

java FastScannerTest < fast-scanner-test-sample.in > fast-scanner-test-sample.out

References:

A part of credit of this blog is given to the author of the following article.

Теги scanner, fastscanner, printwriter

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en4 Английский mason_24 2022-05-30 02:01:13 40
en3 Английский mason_24 2022-05-30 02:00:03 0 (published)
en2 Английский mason_24 2022-05-30 01:57:51 28
en1 Английский mason_24 2022-05-30 01:56:20 3876 Initial revision (saved to drafts)