Data Structures, Algorithms, & Applications in Java
Chapter 17, Exercise 33

To input a weighted digraph we first input the number of vertices and edges in the new digraph; verify that these numbers are legitimate (i.e., neither is less than zero and the number of edges does not exceed the number of edges in a complete digraph with the given number of vertices); allocate a 2D array a[][] of the needed size; and finally read in the edges one by one. Each edge can be added to the data structure being constructed using the method putEdge. Recall that putEdge validates the edge data. Therefore, we need not validate edge data that is input by us.

The code is given below. A test program, input, and output are given in the files ExtendedWAdjacencyDigraph.*.
public class ExtendedAdjacencyWDigraph extends AdjacencyWDigraph
{
   // constructors
   public ExtendedAdjacencyWDigraph(int theVertices)
      {super(theVertices);}
   
   // default is a 0 vertex graph
   public ExtendedAdjacencyWDigraph()
      {super(0);}
   
   /** input a weighted digraph and store as this
     * @param inputMethod input method to use
     * @param inStream input stream for input */
   public void input(Method inputMethod, MyInputStream inStream)
   {
      // input number of vertices and edges
      System.out.println("Enter the number of vertices in the digraph");
      n = inStream.readInteger();
      if (n < 0)
         throw new MyInputException
                   ("number of vertices must be >= 0");

      System.out.println("Enter the number of edges in the digraph");
      int numOfEdges = inStream.readInteger();
      if (numOfEdges < 0)
         throw new MyInputException
                   ("number of edges must be >= 0");

      if (numOfEdges > n * (n - 1))
         throw new MyInputException("too many edges");

      // create a new 2D array a[][], initial values are null
      a = new Object [n + 1][n + 1];
      e = 0;    // reset current number of edges to zero
   
      // now input the edges and add them to a[][]
      WeightedEdge newEdge = new WeightedEdge(0, 0, null);
      Object [] inputMethodArgs = {inStream};
      for (int i = 1; i <= numOfEdges; i++)
      {
         System.out.println("Enter edge " + i);
         newEdge.vertex1 = inStream.readInteger();
         newEdge.vertex2 = inStream.readInteger();
         try
         {
            newEdge.weight = 
               (Operable) inputMethod.invoke(null, inputMethodArgs);
         }
         catch (Exception e)
         {
            throw new IllegalArgumentException
                      ("input: static method input() not defined");
         }
         putEdge(newEdge);
      }
   }
}