Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 06 Jun, 2021

Though C++ is the dominating language in the competitive programming universe, there is a fair share of users who still continue to use Java. If you are comfortable with Java and want to pursue Competitive Programming with it, here’s how to set up your environment on your local computer. As an editor, we will be using one of the most popular code editors of today i.e. 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 this :

{

// 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.

// Example:

// “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

  • Template for CP is the name of the snippet. It is used to identify the snippet while it appears during code-completion (marked in red).

  • template is the prefix which is used to trigger the code-completion (marked in green).
  • body is where the code of the snippet lies. Some important points to note here is:
    • The Fast I/O code is a slight modification of the FastReader code from the article Fast I/O in Java in Competitive Programming.
    • The modification lies in the try/catch block in the constructor of the FastReader class. It is used to connect to the input and output file on our local computer. We will look at the process to set up input and output files later in this article.
    • $0 in the main function is used as a placeholder for the cursor. After the snippet pastes itself on your Java file, the cursor will be automatically placed at the $0 mark. 
    • Comments can be added in the snippet with the keyword $LINE_COMMENT placed before the comment.
    • Special characters, (like quotation marks) must be escaped using backslash (\);
    • It is important to note that, every line in the body of the snippet must be individually placed in quotes and a comma must be placed after every line, as illustrated below.



  • description is used to leave a short note about the snippet for future reference.

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: 

  • Create a separate folder and create two text files in it: “input.txt” and “output.txt“. It is imperative that your Java code file be in that same folder. This should be enough to do the trick. In case you want to put the input, output, and Java files in different directories, put the path of the files in your code in the places shown below.

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 illsutrated 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 4: Partitioning your screen

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

  • Open up VS Code and open the folder which contains your input, output, and Java program file. To achieve this, go to File-> Open Folder and select your folder.
  • Open all three files simultaneously so that they are in separate tabs.
  • Go to View-> Editor Layout-> Two Rows Right.

  • Drag the input.txt to the top-right pane and the output.txt to the bottom-right pane or vice-versa, according to your convenience. Keep your Java file in the left-pane to give it maximum screen coverage. Adjust the sizes of the panes by dragging the borders of each pane division.
  • The final product should look something like this:

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

Attention reader! Don’t stop learning now. Get hold of all the important Comcompetitivepetitve Programming concepts with the Competitive Programming Live  course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :