
public class LinearEquations
{

  // Declaration of the Native (C) function
  private native int f04arc(int n, double[] a, int tda, double[] b,
                             double[] x);

  static
    {
      // The runtime system executes a class's static
      // initializer when it loads the class.
      System.loadLibrary("nagCJavaInterface");
    }

  // The main program
  public static void main(String[] args)
    {
      double a[], b[], x[], r[], copyA[];
      int i, j, n, tda, retCode;

      // Create an object of class LinearEquations
      LinearEquations lineq = new LinearEquations();

      n = 3;
      tda = n;

      a = new double[n*n];
      b = new double[n];
      x = new double[n];
      r = new double[n];
      copyA = new double[n*n];

      a[0*n + 0] = 33.0;
      a[0*n + 1] = 16.0;
      a[0*n + 2] = 72.0;
      a[1*n + 0] = -24.0;
      a[1*n + 1] = -10.0;
      a[1*n + 2] = -57.0;
      a[2*n + 0] = -8.0;
      a[2*n + 1] = -4.0;
      a[2*n + 2] = -17.0;

      b[0] = -359.0;
      b[1] = 281.0;
      b[2] = 85.0;

      // Copy matrix A for later use (it gets overwritten by f04arc).
      for (i = 0; i < n * n; i++)
        copyA[i] = a[i];

      System.out.println();
      System.out.println("Call of NAG linear equation solver routine f04arc");
      System.out.println();

      // Print the input matrix A and vector b
      System.out.println("Input matrix A:");
      for (i = 0; i < n; i++)
        {
          for (j = 0; j < n; j++)
            System.out.print(" " + a[i*n + j]);
          System.out.println();
        }
      System.out.println();

      System.out.println("Input vector b:");
      for (i = 0; i < n; i++)
        System.out.println(" " + b[i]);
      System.out.println();

      // Call method f04arc of object lineq
      retCode = lineq.f04arc(n, a, tda, b, x);

      System.out.print("Return code from f04arc = ");
      System.out.println(retCode);
      System.out.println();

      if (retCode == 0)
        {
          // Print the solution vector x
          System.out.print("Solution vector x:\n");
          for (i = 0; i < n; i++)
            System.out.println(" " + x[i]);
          System.out.println();

          // Calculate and print residual vector
          for (i = 0; i < n; i++)
            {
              r[i] = -b[i];
              for (j = 0; j < n; j++)
                r[i] += copyA[i*n + j] * x[j];
            }
          System.out.print("Residual vector r = A * x - b:\n");
          for (i = 0; i < n; i++)
            System.out.println(" " + r[i]);
          System.out.println();
        }
    }
}
