A Good Example Of A Loop in Java


import java.io.*;

class main
{
   public static void main(String[] args)
   {
      int[][] matrix = new int[3][3];
      //initialize a matrix
      for (int Row =0; Row < 3; Row++)
      {
         for (int Column =0; Column < 3; Column++)
         {
            matrix[Row][Column] = (Row+1) + (Column+1);
         }
      }
      //find if a number is contained in the matrix and output
      boolean found = false;
      int Row = 0;
      while (!found && Row < 3)
      {
         int Column = 0;
         while (!found && Column < 3)
         {
            if (matrix[Row][Column] ==  2)
            {
               System.out.println("2 can be found at position " + (Row+1) + '-' + (Column+1));
               found = true;
            }
         }
      }
      //output the matrix
      System.out.println("The matrix is:");
      for (Row=0; Row < 3; Row++)
      {
         for (int Column=0; Column <3; Column++)
         {
            System.out.print(matrix[Row][Column] + " ");
         }
         System.out.println();
      }
      System.out.println();
   }
}






This page was modified by Tanya Douglas at: Sunday, 25-Mar-2012 18:08:08 CST.
Copyright: Department of Computer Science, University of Regina of Regina.


[CS Department]