Open In App

Java Competitive Programming Setup in VS Code with Fast I/O and Snippets

Though C++ is the dominating language in the competitive programming universe, there is a fair share of users who still continue to use Java as it has been there seen in the development arena and at the same time can be used competitive programming being fast as it can be toggled to and from where python being slowest among dynamic is hardly seen in the competitive world. So users who are comfortable with programming in Java only and wanted to pursue competitive programming with it, here’s how to set up your environment on the local computer. As an editor, we will be using one of the most popular code editors as of today that is VS Code.

Procedure:



Follow the standard steps sequentially to set up. There are 4 steps to be followed as follows:

  1. Install VS Code and set up JDK (if not installed). Let us carry on.
  2. Set up a snippet for the Fast I/O.
  3. Setting up your input and output files.
  4. Partitioning your screen.

Now we will be digging down to each step alongside visual aids right from the starting to get absolutely clear understanding geek as they last longer.



Explanation:

Step 1: Install VS Code and set up JDK 

Step 2: Set up a snippet for the Fast I/O.

Snippets are very useful to quickly insert a large amount of pre-written code that you use frequently. Since the input and output code will be used for every competitive programming problem, a snippet will be extremely helpful to our cause.

To set up a snippet, observe the following steps:

2.1 Open up VS Code and go to File -> Preferences -> User Snippets.

2.2 Select java.json from the succeeding drop-down box as shown below.

2.3 You will find VS Code already provides a rough guide on how to create a custom snippet. The text should look something like as follows:

{

Place your snippets for java here. Each snippet is defined 
under a snippet name and has a prefix, body and 
description. 

The prefix is what is used to trigger the snippet and
the body will be expanded and inserted. Possible variables are:

$1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders.
Placeholders with the 
same ids are connected.

Illustration:


"Print to console": {
"prefix": "log",
"body": [
"console.log('$1');",
"$2"
],
"description": "Log output to console"

}
}

2.4 Below the given comments and inside the curly braces, paste the following code:

"Template for CP" : {
        "prefix": "template",
        "body":[
            "import java.util.*;",
            "import java.io.*;",
            
            "public class Main {",
                "$LINE_COMMENT For fast input output",
                "static class FastReader {",
                    "BufferedReader br;",
                    "StringTokenizer st;",
             
                    "public FastReader()",
                    "{ try {br = new BufferedReader(",
                        "new FileReader(\"input.txt\"));",
                        "PrintStream out = new PrintStream(new FileOutputStream(\"output.txt\"));",
                        "System.setOut(out);}",
                    "catch(Exception e) { br = new BufferedReader(new InputStreamReader(System.in));}",
                    "}",
             
                    "String next()",
                    "{",
                        "while (st == null || !st.hasMoreElements()) {",
                            "try {st = new StringTokenizer(br.readLine());}",
                            "catch (IOException e) {",
                                "e.printStackTrace();}",
                        "}",
                        "return st.nextToken();",
                    "}",
             
                    "int nextInt() { return Integer.parseInt(next()); }",         
                    "long nextLong() { return Long.parseLong(next()); }",         
                    "double nextDouble() {return Double.parseDouble(next()); }",
             
                    "String nextLine()",
                    "{",
                        "String str = \"\";",
                        "try {",
                        "str = br.readLine();",
                        "}",
                        "catch (IOException e) {",
                            "e.printStackTrace();",
                        "}",
                        "return str;",
                    "}",
                "}",
                "$LINE_COMMENT end of fast i/o code",
            
                
                "public static void main(String[] args) {",
                    "FastReader reader = new FastReader();",
                    "$0",
            "}",
        "}"
        ],
        "description": "template for cp in java"
    },

    "For loop":{
        "prefix" : "forl",
        "body" : [
            "for(int i = 0; i < $0; i++)"
        ]
    }                        

Note: Explanation of the above snippet is provided and is necessary to understand in order to understand its usage and further modification

Tip: When the snippet is implemented in your program, it appears in an unformatted and un-indented form. To quickly format it, press Shift + Alt + F.

Step 3: Setting up your input and output files.

During competitions, it is easier to paste a large input and read the corresponding output from files rather than manually entering input in your terminal window. Therefore, we will set up an input and output file. The steps to take so are as follows: 

We need to look closely at the following code snippet to get to know how the try/catch block works here which is provided below in the example.

Example

// This code snippet is a part of the FastReader class
// as illustrated above

public FastReader() {

  // The try block runs when both input and output files
  // are present in the specified directory.
  try {

    // We modify the input stream to take input
    //from the  input.txt file
    br = new BufferedReader(new FileReader("input.txt"));

    // We modify the output stream to print the output
    // in the output.txt file
    PrintStream out = new
    PrintStream(new FileOutputStream("output.txt"));

    System.setOut(out);
  }

  // In case the input or the output file is not found,
  // a FileNotFoundException is thrown and we enter the
  // catch block.

  // Catch block to handle th exception
  catch (Exception e) {

    // Since an input file is not present, we take input
    // from the usual system input stream.
    br = new BufferedReader(
      new InputStreamReader(System.in));
  }
}

Explanation of the above snippet is as follows:

Here basically we are looking for an input and output file first, which should be present on our local device, and input and output there. However, if an input and output text file is not found, as is the case of when the code is submitted to an online judge, the program will read input from the standard input stream and output in the standard output stream.

Step 3 ( Alternative ): Setting up your input and output files.

During competitions, it is easier to paste a large input and read the corresponding output from files rather than manually entering input in your terminal window. Therefore, we will set up an input and output file. The steps to take so are as follows: 

Example

// This code snippet is a part of the FastReader class
// as illustrated above

public FastReader() {

  // The try block runs when both input and output files
  // are present in the specified directory.
  try {

    //The Extension will PIPE the Input and Output Stream to Files at Runtime
    br = new BufferedReader(System.in);
  }

  // In case there is an error input or the output file is not found,
  // Exception is thrown and we enter the
  // catch block.

  // Catch block to handle the exception
  catch (Exception e) {

    // Printing the Stack Trace of Exception
    e.printStackTrace();
  }
}

Step 4: Partitioning your screen

Now, that all the necessary files have been created, let us set up our coding environment:

Tip: You can switch quickly between panes using Ctrl + PgUp and Ctrl + PgDown key combinations.


Article Tags :