Java

OOP GUIDE / WORK

 

DATA CLASS SOLUTIONS

 

 

TASK – PART 1 – QUESTION

 

No solution required.

 

 

TASK – PART 2 – REQUIRED CLASS

No solution required.

 

 

TASK – PART 3 – IMPLEMENT THE DATA CLASS

 

 

public class Data

{

     public static final int MAX = 1000; //value needed for implementation

     private int[][] grid;

    

     //This constructor was added so that we can implement the Data class.

     public Data(int[][] tmpGrid)

     {

           grid = tmpGrid;

     }

    

     /**Fills all elements of grid with randomly generated values, as described in part A

      * Precondition: grid is not null

      *    grid has at least one element

      */

    

     public void repopulate()

     {

           //to be implemented in part A

           for (int r=0; r<grid.length; r++)

           {

                for (int c=0; c<grid[r].length; c++)

                {

                      grid[r][c] = (int)(Math.random() * MAX) + 1;  //1 to MAX

                      while(grid[r][c] % 10 != 0 || grid[r][c] % 100 == 0)

                      {

                           grid[r][c] = (int)(Math.random() * MAX) + 1;  //1 to MAX

                      }

                }

           }

     }

    

     /**Return the number of colours in grid that are in increasing order, as described

      * in part B

      * Precondition: grid is not null

      *    grid has at least one element

      */

    

     public int countIncreasingCols()

     {

           //to be implemented in part B

           int incCols = 0;

          

           for (int c=0; c<grid[0].length; c++)   //assuming rectangular 2D array

           {

                boolean increasing = true;

                for (int r=0; r<grid.length-1; r++)

                {

                      if (grid[r][c] > grid[r+1][c])

                      {

                           increasing = false;

                      }

                }

               

                if (increasing == true)

                {

                      incCols++;

                }

           }

           return incCols;

     }

    

     //Added to display grid's content

     public String toString()

     {

           String s = "";

           for (int r=0; r<grid.length; r++)

           {

                for (int c=0; c<grid[r].length; c++)

                {

                      s = s + grid[r][c] + " ";

                }

                s = s + "\n";

           }

           return s;

     }

}

 



 

TASK – PART 4 – TESTING

No solution required.