Question
Lab Multidimensional Arrays Animation of Multidimensional Programming Activity Lab Objectives ? Be able to declare two-dimensional arrays ? Be able to pass two-dimensional arrays to
Lab Multidimensional Arrays
Animation of Multidimensional Programming Activity
Lab Objectives
? Be able to declare two-dimensional arrays
? Be able to pass two-dimensional arrays to methods
? Be able to return a two-dimensional array from methods
? Be able to process a two-dimensional array in a Java Method
? Be able to work with individual rows and columns in a two-dimensional array
Introduction
Writing methods that take multi-dimensional arrays as parameters and/or return multi-dimensional arrays is similar to working with single-dimensional arrays.
The syntax for a method that accepts a two-dimensional array as a parameter is as follows:
returnType methodName( arrayType[][] arrayParameterName )
The syntax for a method that returns a two-dimensional array is the following:
returnArrayType [][] methodName( arrayType [ ][ ] arrayParameterName )
In this Lab, you will work with a 4-row, 20-column, two-dimensional array of integers. You will write methods that perform the following operations:
Fill the 2-D array with random numbers between 50 and 80.
Print the array.
Set every array element of a given row to a specified value. The value is a parameter of a method.
Find the minimum value in a given column of the array. The column is a parameter of a method.
Count the number of elements of the array having a specified value. The value is a parameter of a method
To visualize how the two-dimensional array is working, your result will animate a bar graph. The
Code for the bar graph is provided to you as BarChart.java. So, the framework for this lab will animate your algorithm, which will support you in checking the accuracy of your Java program.
Lab Instructions
The source files required to complete this activity has been provided. Copy both the files to a folder in your computer. It is important that both the files stay in the same folder.
Open the TwoDimArrayPractice.java source file. For your convenience, the sample code for task number 1 has been provided under comment 1. inside the fillValues() method. You may use this as a model for completing the remaining four tasks. You will need to complete those rest of the four tasks in four other methods. In each one of these four remaining tasks, you will fill in the code for a method that will manipulate an existing array of 4 rows and 20 columns. You need not instantiate the two-dimensional array. That has been done for you.
SAMPLE OUTPUT:
Following shows a sample output from the fillValues( ) method.
Task #1 Print Array to Console.
For printing array to console, please make a complete implementation of the method:
public void printArray( )
This method is under comment 2.
For console printing, elements are separated by a space. The instance variable named intArray is the integer array to be printed.
To animate the algorithm, put this method call as the last element in your inner for loop animate( row, column ); Here row is the index of the array's current row, and column is the index of the array's current column.
OUTPUT:
Following shows the screen capture of the required output from the printArray( ) method.
Task #2 Set All Elements in A Row to A Specified Value
This is under comment 3. Please, implement the setValues( int value, int row ) method that sets all the elements in the specified row to a specified value.
The instance variable named intArray is the integer array.
To animate the algorithm, put this method call as the last element in your for loop animate( row, column ); Here row is the index of the array's current row and column is the index of the array's current column.
OUTPUT:
Following shows the screen capture of the required output from setValues(65, 2).
Task #3 Find Minimum Value in the Specified Column
Implement the method public int findMinimum( int column ) that finds the minimum value in the specified column.
Again, the instance variable named intArray is the integer array
To animate the algorithm, put this method call as the last element in your for loop animate( row, column ); Here row is the index of the array's current row and column is the index of the array's current column
Notice that a dummy return statement (return 0) is provided at the end of public int findMinimum( int column ) method so that the source code will compile in its present state. In this way, you can write and test each method separately, which is known as the step-wise refinement. When you are ready to write the public int findMinimum( int column ) method, just replace the dummy return statement with the appropriate return statement for the method.
Following shows screen shot of the output for findMinimum(3).
OUTPUT:
Task #4 Find Frequency of a Given Value in the Array
Implement the method public int countFound( int value ) that counts the number of times a given value is found in the array.
The instance variable named intArray is the integer array.
To animate the algorithm, put this method call as the last element in your for loop animate( row, column ); Here row is the index of the array's current row and column is the index of the array's current column
Notice that a dummy return statement (return 0) is provided at the end of public int countFound( int value ) method so that the source code will compile in its present state. In this way, you can write and test each method separately using the step-wise refinement. When you are ready to write the public int countFound( int value ) method, just replace the dummy return statement with the appropriate return statement for the method.
OUTPUT:
Following shows screen capture for countFound(66).
The two .java files (TwoDimArrayPrac.java and BarChart.java) running under the same project will animate your algorithm so that you can visually watch your code work. For this to happen, make sure that your single or nested for loops call the method animate. The arguments that you send to animate are not always the same and the location of the call to animate will differ depending on the task you are coding.
Since the values in the two-dimensional array are randomly generated, the values will be different each time the program runs. To test any of the methods that you have implemented, please click on the appropriate button.
/* * BarChart Code */ import java.awt.Graphics; import java.awt.Image; import java.awt.image.*; import javax.swing.JFrame; import java.awt.Color; public class BarChart implements ImageObserver { public static final int XMAX = 400; public static final int XSTART = 60; public static final int [] YMAX = { 220, 320, 420, 520 }; // hard code an array of 4 colors private Color [] colors = { Color.BLUE, new Color( 150, 150, 0 ), Color.DARK_GRAY, Color.MAGENTA }; private int [][] data; private int barSize; private int xStart; private int activity = 5; private int count = 0; private int studentResult; private int exactFrequencyCount; private int exactMinimum; private int key; private boolean checkNewValues; public BarChart( ) { } public BarChart( int [][] dArray ) { data = new int [dArray.length][dArray[0].length]; for ( int i = 0; i < dArray.length; i++ ) { for ( int j = 0; j < dArray[i].length; j++ ) { data[i][j] = dArray[i][j]; } } barSize = ( XMAX - 20 ) / data[0].length; studentResult = -1; exactFrequencyCount = -1; exactMinimum = -1; key = -1; checkNewValues = true; } public void setArray( int [][] dArray ) { for ( int i = 0; i < dArray.length; i++ ) { for ( int j = 0; j < dArray[i].length; j++ ) { data[i][j] = dArray[i][j]; } } } public void setStudentResult( int newStudentResult ) { studentResult = newStudentResult; } public void setKey( int newKey ) { key = newKey; } public int getExactFrequencyCount( ) { return exactFrequencyCount; } public int getExactMinimum( ) { return exactMinimum; } public boolean getCheckNewValues( ) { return checkNewValues; } public void setActivity( int a ) { activity = a; } public int getActivity( ) { return activity; } public void updateBarChart( int key, int index1, int index2, Graphics g ) { draw( g ); switch( activity ) { case( 0 ): // create new array values // drawNewArray( index1, index2, g ); break; case( 1 ): // print out the array drawArray( index1, index2, g ); break; case( 2 ): // set all array values of a row to a certain value drawNewValue( index1, index2, g ); break; case( 3 ): // find the minimum in a row drawMinimum( index1, index2, g ); break; case( 4 ): // find the frequency of a value drawFrequency( index1, index2, key, g ); break; } } public void draw( Graphics g ) { // Draws the original array in 4 colors for ( int i = 0; i < data.length; i++ ) { xStart = XSTART; g.setColor( colors[i] ); g.drawString( "Row " + i, xStart - 50, YMAX[i] ); for ( int j = 0; j < data[i].length; j++ ) { g.fillRect( xStart, YMAX[i]-data[i][j], barSize-5, data[i][j] ); g.drawString( "" + data[i][j], xStart, YMAX[i] + 15 ); xStart += barSize; } } } public void drawArray( int index1, int index2, Graphics g ) { // called to "print out the array" // index1 must be less than 4 g.setColor( Color.red ); for ( int i = 0; i < index1; i++ ) { xStart = XSTART; for ( int j = 0; j < data[i].length; j++ ) { g.fillRect( xStart, YMAX[i]-data[i][j], barSize-5, data[i][j] ); g.drawString( "" + data[i][j], xStart, YMAX[i] + 15 ); xStart += barSize; } } xStart = XSTART; for ( int j = 0; j <= index2; j++ ) { g.fillRect( xStart, YMAX[index1]-data[index1][j], barSize-5, data[index1][j] ); g.drawString( "" + data[index1][j], xStart, YMAX[index1] + 15 ); xStart += barSize; } } public void drawNewValue( int index1, int index2, Graphics g ) { g.setColor( Color.blue ); String s = ""; checkCurrentNewValues( index1, index2 ); if ( checkNewValues ) s = "correctly"; else s = "incorrectly"; g.drawString( "Setting new array elements of row " + index1 + " to " + key, 25, 110 ); g.drawString( "Up to index " + index2 + " , the new values are set " + s, 25, 130 ); // set all values of a row to a certain value g.setColor( Color.red ); xStart = XSTART; // g.drawString( "" + data[index1][index2], xStart, YMAX[index1] + 15 ); for ( int j = 0; j <= index2; j++ ) { g.drawString( "" + data[index1][index2], xStart, YMAX[index1] + 15 ); g.fillRect( xStart, YMAX[index1]-data[index1][j], barSize-5, data[index1][j] ); xStart += barSize; } } public void drawMinimum( int index1, int index2, Graphics g ) { int b = findSubMinimum( index1, index2 ); if ( index2 != -1 ) { g.setColor( Color.BLUE ); g.drawString( "Your current minimum in column " + index2 + ": " + studentResult, 25, 110 ); exactMinimum = b; g.drawString( "Correct current minimum in column " + index2 + ": " + exactMinimum, 25, 130 ); g.setColor( Color.RED ); xStart = XSTART + index2 * barSize; g.drawRect( xStart, YMAX[index1] - data[index1][index2], barSize-5, data[index1][index2] ); g.drawString( "" + data[index1][index2], xStart, YMAX[index1] + 15 ); for ( int i = 0; i <= index1; i++ ) { if ( data[i][index2] == b ) { g.setColor( Color.RED ); g.fillRect( xStart, YMAX[i] - data[i][index2], barSize-5, data[i][index2] ); break; } } } } public int findSubMinimum( int index1, int index2 ) { int minimum = data[0][index2]; for ( int i = 1; i <= index1; i++ ) { if ( minimum > data[i][index2] ) minimum = data[i][index2]; } return minimum; } public void drawFrequency( int index1, int index2, int value, Graphics g ) { // called to count frequency of a value // index1 must be less than 4 // index2 must be less than 20 g.setColor( Color.BLUE ); g.drawString( "Your current frequency count: " + studentResult, 25, 110 ); exactFrequencyCount = findExactFrequencyCount( index1, index2, value ); g.drawString( "Correct current frequency count: " + exactFrequencyCount, 25, 130 ); g.setColor( Color.RED ); for ( int i = 0; i < index1; i++ ) { xStart = XSTART; for ( int j = 0; j < data[i].length; j++ ) { if ( data[i][j] == value ) g.fillRect( xStart, YMAX[i]-data[i][j], barSize-5, data[i][j] ); xStart += barSize; } } // last row (incomplete) xStart = XSTART + barSize * index2; g.drawRect( xStart, YMAX[index1]-value, barSize-5, value ); g.drawString( "" + data[index1][index2], xStart, YMAX[index1] + 15 ); xStart = XSTART; for ( int j = 0; j <= index2; j++ ) { if ( data[index1][j] == value ) g.fillRect( xStart, YMAX[index1]-data[index1][j], barSize-5, data[index1][j] ); xStart += barSize; } } public int findExactFrequencyCount( int rowIndex, int colIndex, int searchValue ) { int currentCount = 0; for ( int i = 0; i < rowIndex; i++ ) { for( int j = 0; j < data[i].length; j++ ) { if ( data[i][j] == searchValue ) currentCount++; } } // check current row now for (int j = 0; j <= colIndex; j++ ) { if ( data[rowIndex][j] == searchValue ) currentCount++; } return currentCount; } public void checkCurrentNewValues( int index1, int index2 ) { checkNewValues = true; for ( int i = 0; i <= index2; i++ ) { if ( key != data[index1][i] ) checkNewValues = false; } } public boolean imageUpdate( Image i, int infoflags, int x, int y, int width, int height ) { return true; } }
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
/* TwoDimArrayPractice * Students Work with this Java file * On Multi-dimensional Arrays */ import java.awt.*; import javax.swing.*; import javax.swing.JOptionPane; import java.awt.event.*; import java.util.*; public class TwoDimArrayPractice extends JFrame { // GUI components private JButton fillValues; private JButton printArray; private JButton setValues; private JButton findMinimum; private JButton countFrequency; private ButtonHandler bh; private static int [][] intArray; private final int ROWS = 4; private final int COLUMNS = 20; private static int current1 = -1; private static int current2 = -1; private int key; private int rowSelected = -1; private int columnSelected = -1; private BarChart bc; private static int counter = 0; private static TwoDimArrayPractice app; private boolean firstTime = true; private Image offscreen; public TwoDimArrayPractice( ) { super( "Choose your activity" ); Container c = getContentPane( ); c.setLayout( new FlowLayout( ) ); fillValues = new JButton( "Fill Values" ); c.add( fillValues ); printArray = new JButton( "Print Array" ); c.add( printArray ); setValues = new JButton( "Set Values" ); c.add( setValues ); findMinimum = new JButton( "Find Minimum" ); c.add( findMinimum ); countFrequency = new JButton( "Count Frequency" ); c.add( countFrequency ); bh = new ButtonHandler( ); fillValues.addActionListener( bh ); printArray.addActionListener( bh ); setValues.addActionListener( bh ); findMinimum.addActionListener( bh ); countFrequency.addActionListener( bh ); setSize( 500,550 ); intArray = new int[ROWS][COLUMNS]; // fill with random numbers between 50 and 80 Random rand = new Random( ); for ( int i = 0; i < intArray.length; i++ ) { for ( int j = 0; j < intArray[0].length; j++ ) { intArray[i][j] = rand.nextInt( 31 ) + 50; } } bc = new BarChart( intArray ); // print the array values System.out.println( "Row\tValue" ); for ( int i = 0; i < intArray.length; i++ ) { System.out.print( i + "\t" ); for ( int j = 0; j < intArray[i].length; j++ ) { System.out.print( intArray[i][j] + " " ); } System.out.println( ); } System.out.println( ); setVisible( true ); offscreen = this.createImage( getSize( ).width, getSize( ).height ); } // 1. This method has been coded as an example /** Fills the array with random numbers between 50 and 80 * The instance variable named intArray is the integer array to be * filled with values */ public void fillValues( ) { Random rand = new Random( ); for ( int row = 0; row < intArray.length; row++ ) { System.out.print( row + "\t" ); for ( int column = 0; column < intArray[row].length; column++ ) { intArray[row][column] = rand.nextInt( 31 ) + 50; animate( row, column ); // needed to create visual feedback } System.out.println( ); } } // end of fillValues method // 2. Student writes this method /** Prints array to the console, elements are separated by a space * The instance variable named intArray is the integer array to be printed */ public void printArray( ) { // Note: To animate the algorithm, put this method call as the // last element in your inner for loop // animate( row, column ); // where row is the index of the array's current row // and column is the index of the array's current column // Write your code here: } // end of printArray method // ***** 3. Student writes this method /** Sets all the elements in the specified row to the specified value * The instance variable named intArray is the integer array * @param value the value to assign to the element of the row * @param row the row in which to set the elements to value */ public void setValues( int value, int row ) { // Note: To animate the algorithm, put this method call as the // last element in your for loop // animate( row, column ); // where row is the index of the array's current row // and column is the index of the array's current column // Write your code here: } // end of setValues method // 4. Student writes this method /** Finds minimum value in the specified column * The instance variable named intArray is the integer array * @param column the column to search * @return the minimum value found in the column */ public int findMinimum( int column ) { // Note: To animate the algorithm, put this method call as the // last element in your for loop // animate( row, column, minimum ); // where row is the index of the array's current row, // column is the index of the array's current column // minimum is the local variable storing the current minimum // Write your code here: return 0; // replace this line with your return statement } // end of findMinimumn method // 5. Student writes this method /** Finds the number of times value is found in the array * The instance variable named intArray is the integer array * @param value the value to count * @return the number of times value was found */ public int countFound( int value ) { // Note: To animate the algorithm, put this method call as the // last element in your inner for loop // animate( row, column, num ); // where row is the index of the array's current row, // column is the index of the array's current column, and // num is the local variable storing the current frequency count // Write your code here: return 0; // replace this line with your return statement } // end of countFound method public void startActivity( int act ) { bc.setActivity( act ); boolean goodInput = false; String answer = ""; switch( act ) { case( 0 ): fillValues( ); JOptionPane.showMessageDialog( null, "Array filled with new values" ); break; case( 1 ): printArray( ); JOptionPane.showMessageDialog( null, "Array printed" ); break; case( 2 ): while ( !goodInput || key < 50 || key > 80 ) { try { answer = JOptionPane.showInputDialog( null, "Enter a value between 50 and 80" ); if ( answer != null ) { key = Integer.parseInt( answer ); goodInput = true; } else { goodInput = false; break; } } catch( Exception e ) {} } if ( goodInput ) { goodInput = false; while ( !goodInput || rowSelected < 0 || rowSelected > 3 ) { try { answer = JOptionPane.showInputDialog( null, "Enter a row number between 0 and 3" ); if ( answer != null ) { rowSelected = Integer.parseInt( answer ); goodInput = true; } else { goodInput = false; break; } } catch( Exception e ) {} } } if ( goodInput ) { bc.setKey ( key ); setValues( key, rowSelected ); String message = ""; if ( bc.getCheckNewValues( ) ) message = " correctly"; else message = " incorrectly"; JOptionPane.showMessageDialog( null, "Values in row " + rowSelected + " set to " + key + message ); } break; case( 3 ): while ( !goodInput || columnSelected < 0 || columnSelected > 19 ) { try { answer = JOptionPane.showInputDialog( null, "Enter a column number between 0 and 19" ); if ( answer != null ) { columnSelected = Integer.parseInt( answer ); goodInput = true; } else { goodInput = false; break; } } catch( Exception e ) {} } if ( goodInput ) { int a = findMinimum( columnSelected ); String feedbackMin = ""; if ( a == bc.getExactMinimum( ) ) feedbackMin = " This is correct"; else feedbackMin = " This is incorrect"; String displayMessageMin = "In column " + columnSelected + ", you found a minimum value of "; displayMessageMin += a + feedbackMin; JOptionPane.showMessageDialog( null, displayMessageMin ); } break; case( 4 ): while ( !goodInput || key < 50 || key > 80 ) { try { answer = JOptionPane.showInputDialog( null, "Enter a value between 50 and 80" ); if ( answer != null ) { key = Integer.parseInt( answer ); goodInput = true; } else { goodInput = false; break; } } catch( Exception e ) {} } if ( goodInput ) { int frequency = countFound( key ); String feedbackFrequency = ""; if ( frequency == bc.getExactFrequencyCount( ) ) feedbackFrequency = " This is correct"; else feedbackFrequency = " This is incorrect"; String plural = ""; if ( frequency != 1 ) plural = "s"; String displayMessageFrequency = "You found " + key + " " + frequency + " time" + plural; displayMessageFrequency+= feedbackFrequency; if ( frequency != -1 ) JOptionPane.showMessageDialog( null, displayMessageFrequency ); else JOptionPane.showMessageDialog( null, "You did not find the value " + key ); } break; } enableButtons( ); } public static int getCurrent1( ) { return current1; } public static int getCurrent2( ) { return current2; } public static int getCounter( ) { return counter; } public static int [][] getArray( ) { return intArray; } private void animate( int row, int column ) { if ( bc.getActivity( ) >= 0 && bc.getActivity( ) <= 2 ) { try { current1 = row; current2 = column; bc.setArray( intArray ); Graphics g = offscreen.getGraphics( ); paint( g ); g = this.getGraphics( ); g.drawImage( offscreen, 0, 0, this ); if ( bc.getActivity( ) == 0 ) Thread.sleep( 200 ); else Thread.sleep( 500 ); } catch ( InterruptedException e ) { System.out.println( "IE Exception " + e.getMessage( ) ); System.out.println( e.toString( ) ); } } else { // call to animate with wrong number of arguments JOptionPane.showMessageDialog( null, "Wrong number of arguments to animate method" ); System.exit( 1 ); } } private void animate( int row, int column, int intermedResult ) { if ( bc.getActivity( ) == 3 || bc.getActivity( ) == 4 ) { try { current1 = row; current2 = column; bc.setStudentResult( intermedResult ); bc.setArray( intArray ); Graphics g = offscreen.getGraphics( ); paint( g ); g = this.getGraphics( ); g.drawImage( offscreen, 0, 0, this ); Thread.sleep( 500 ); } catch ( InterruptedException e ) { System.out.println( "IE Exception " + e.getMessage( ) ); System.out.println( e.toString( ) ); } } else { // call to animate has wrong number of arguments JOptionPane.showMessageDialog( null, "Wrong number of arguments to animate method" ); System.exit( 1 ); } } public void paint( Graphics g ) { if ( ( current1 != -1 && current2 != -1 ) || firstTime ) { super.paint( g ); bc.draw( g ); bc.updateBarChart( key, current1, current2, g ); firstTime = false; } } public static void main( String [] args ) { app = new TwoDimArrayPractice( ); app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } public void disableButtons( ) { fillValues.setEnabled( false ); printArray.setEnabled( false ); setValues.setEnabled( false ); countFrequency.setEnabled( false ); findMinimum.setEnabled( false ); } public void enableButtons( ) { fillValues.setEnabled( true ); printArray.setEnabled( true ); setValues.setEnabled( true ); countFrequency.setEnabled( true ); findMinimum.setEnabled( true ); } private class ButtonHandler implements ActionListener { private boolean on = true; public void actionPerformed( ActionEvent e ) { PrintArrayT t = new PrintArrayT( app ); if ( e.getSource( ) == fillValues ) { disableButtons( ); fillValues.requestFocus( ); bc.setActivity( 0 ); disableButtons( ); t.start( ); } else if ( e.getSource( ) == printArray ) { disableButtons( ); printArray.requestFocus( ); bc.setActivity( 1 ); t.start( ); } else if ( e.getSource( ) == setValues ) { disableButtons( ); setValues.requestFocus( ); bc.setActivity( 2 ); t.start( ); } else if ( e.getSource( ) == findMinimum ) { disableButtons( ); findMinimum.requestFocus( ); bc.setActivity( 3 ); t.start( ); } else if ( e.getSource( ) == countFrequency ) { disableButtons( ); countFrequency.requestFocus( ); bc.setActivity( 4 ); t.start( ); } } } public void resetButtonSelection( ) { fillValues.setSelected( false ); printArray.setSelected( false ); setValues.setSelected( false ); findMinimum.setSelected( false ); countFrequency.setSelected( false ); } private class PrintArrayT extends Thread { int [][] arr; TwoDimArrayPractice s1; public PrintArrayT ( TwoDimArrayPractice s ) { arr = TwoDimArrayPractice.intArray; s1 = s; } public void run( ) { startActivity( bc.getActivity( ) ); enableButtons( ); // deselectButtons( ); } } }
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
objective of this lab
Practice with 2D Arrays through animations.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started