Terminating Input in Java

Write here if you have problems with your Java source code

Moderator: Board moderators

Post Reply
skytreader
New poster
Posts: 2
Joined: Tue Jan 19, 2010 3:53 pm

Terminating Input in Java

Post by skytreader » Tue Jan 19, 2010 4:02 pm

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?

skytreader
New poster
Posts: 2
Joined: Tue Jan 19, 2010 3:53 pm

Re: Terminating Input in Java

Post by skytreader » Sun Mar 07, 2010 6:42 pm

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?

smithdwsn
New poster
Posts: 4
Joined: Mon May 24, 2010 8:50 pm

Re: Terminating Input in Java

Post by smithdwsn » Tue May 25, 2010 3:21 pm

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.

Post Reply

Return to “Java”