A Bad 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 i=1; i < 3; i++)
      {
         for (int j=0; j < 3; j++)
         {
            matrix[i][j] = i + (j++);
         }
      }
      //find if a number is contained in the matrix and output
      boolean found = false;
      for (int i=0; i < 3; i++)
      {
         for (int j=0; j <= 2; j++)
         {
            if (matrix[i][j] ==  2)
            {
               System.out.println("2 can be found at position " + (i+1) + '-' + (j+1));
               found = true;
               break;
            }
         }
         if (found)
         {
            break;
         }
      }
      //output the matrix
      System.out.println("The matrix is:");
      for (int i=0; i <= 2; i++)
      {
         for (int j=0; j <=2; j++)
         {
            System.out.print(matrix[i][j] + " ");
         }
         System.out.println();
      }
      System.out.println();
   }
}





This page was modified by Tanya Douglas at: Friday, 21-Aug-2020 15:28:16 CST.
Copyright: Department of Computer Science, University of Regina of Regina.


[CS Department]