Search code examples
javaeclipseinputfile-format

How to use .in files as input for eclipse in Google Code Jam?


I've searched for a solution for a long time but surprisingly nobody seems to have encountered the problem before me.

Google Code Jam gives the input as a .in file. I looked in the solutions to see how people handled this kind of input. I copied the solution to eclipse and put the .in file as the input but the console stayed blank which, I guess means the scanner cannot read the .in file as normal input. How can I read in eclipse the input straight from the .in file?

This is the code use to read the input (again, it doesn't work when tried straight on the .in file).

public class A {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int numberOfCases = in.nextInt();

                    int next  = in.nextInt();

                    //some unimportant piece of code

            System.out.format("Case #%d: %d\n", currentCase, max(bTime, oTime));
        }
    }

I've shortened the code for only the parts that have to do with the question. you can see the full answer at http://www.go-hero.net/jam/11/name/theycallhimtom (under "Bot Trust" -> S).


Solution

  • System.in represents the standard input, which means it's normally read from the keyboard. So, if you started your program and then typed the whole .in file into the console window, it would work.

    But you don't want to have to type the file every time, instead you can redirect the input to read from the .in file instead of the keyboard. As far as I can see, there is no option to do that in Eclipse, but you can do it from the command line by appending < followed by the file name to the normal command to start your program. The whole command could look something like:

    java -jar A.jar < A-small.in
    

    Another option is to take the name of the input file as an argument of your program (that's what the Eclipse option you used is for). Those arguments are accessible from the args parameter of your main method. To do it this way, you actually have to tell Scanner to use that file:

    Scanner in = new Scanner(new File(args[0]));
    

    Yet another option would be to hard-code the file name:

    Scanner in = new Scanner(new File("A-small.in"));
    

    Doing it this way would be considered a bad practice in any kind of production code, but it might be okay for a programming contest.