Page 1 of 1

Terminating Input in Java

Posted: Tue Jan 19, 2010 4:02 pm
by skytreader
Hello. As I see it, the judge uses command-line input. While some problems give a "terminator" input (e.g. if two integers are given per line in an input, the "terminator" input is usually "0 0"), others do not. How do I go about that in Java? This is what I am doing:

Code: Select all

public static void main(String[] args) throws IOException{
        BufferedReader lineInputReader = new BufferedReader(new InputStreamReader(System.in));
        String foo = lineInputReader.readLine();

        while(foo != null){
            String[] bar = foo.split(" ");

            //Some code here concerning the problem...

            foo = lineInputReader.readLine();
        }

        lineInputReader.close();
    }
I received a Runtime Error with the above code and so I guess the judge is complaining about how I handle the (undetermined) last test case. Am I correct in my guess? If so, what is an advisable workaround?

Re: Terminating Input in Java

Posted: Sun Mar 07, 2010 6:42 pm
by skytreader
I've figured it out...somehow :D. I coded a try-catch block. It seems that a try-catch is still necessary even if you are not really expecting an error to occur.

However, I still haven't figured out how to terminate input when the end is not specified (again, in contrast to those problems which specify the number of test cases, or have "terminator" inputs, which usually involves zeroes). My current code template:

Code: Select all

public static void main(String[] args) throws IOException{
        try{
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader lineInputReader = new BufferedReader(isr);
            String foo = lineInputReader.readLine();
            boolean firstTime = true;

            while(foo != null){
                //These conditional lines handle proper line-breaking
                if(firstTime){
                    firstTime = false;
                }
                else{
                    System.out.print("\n");
                }

                //Process input...
                foo = lineInputReader.readLine();
            }

            lineInputReader.close();
            isr.close();
            System.exit(0);
        }
        catch(Exception e){

        }
    }
Anything wrong I'm doing?

Re: Terminating Input in Java

Posted: Tue May 25, 2010 3:21 pm
by smithdwsn
You are right. This is the perfect code for terminating input. You declared and throw exception at right time and proper place. There is no error. It will work well.