Input Processing

There are a few common patterns in which input is provided in programming contest problems. Below, we will discuss some of these patterns. Furthermore, we will show a way to handle these patterns in Java.

Most of the time, the input will consist of multiple test cases. For this, you of course need a loop. Which loop is most appropriate depends on the way that the input is provided.

In many cases, the first line of the input contains an positive integer, say N, which is the number of test case. In this case, a for-loop may be most appropriate.

import java.util.Scanner;
import java.io.PrintStream;

public class
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in );
      PrintStream out = System.out;

      final int N = in.nextInt(); // number of test cases
      for (int n = 0; n < N; n++)
      {
         // process each test case

      }
   }
}

Another common pattern consists multiple test cases, where the last case is a special case, signalling the end of the input. Usually, that last case should not be considered. For example, the first line of each test case contains two integers M and M. The input will terminate with two zeros for M and N. In this case, a do loop might be more appropriate.

import java.util.Scanner;
import java.io.PrintStream;

public class
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in );
      PrintStream out = System.out;

      int m = in.nextInt();
      int n = in.nextInt();
      while (!(m== 0 && n == 0))
      {
         // process the rest of the test case



         m = in.nextInt();
         n = in.nextInt();
      }
   }
}

Testing

Save the sample input given in the programming problem in a file, say A.in. Assuming that your class is called A, you can now test your class using

  java A < A.in