Arrays

download Arrays

If you can't read please download the document

description

Arrays. Chapter 6. Reminders. Project 4 released: due Oct 6 @ 10:30 pm Project 1 regrades due by midnight tonight Project 2 grades posted on WebCT – regrade requests due by Friday Oct 7 midnight (send to [email protected]). Exam 1 Info. Exam will be returned in recitation today - PowerPoint PPT Presentation

Transcript of Arrays

  • ArraysChapter 6

  • Reminders

    Project 4 released: due Oct 6 @ 10:30 pmProject 1 regrades due by midnight tonightProject 2 grades posted on WebCT regrade requests due by Friday Oct 7 midnight (send to [email protected])

  • Exam 1 InfoExam will be returned in recitation todaySolution available on the websiteScores are available on WebCTProblems/scoring errors: talk to your GTAExam 1 Stats:Mean: 73.2Median: 77High: 98

  • Creating and Accessing Arraysexampledouble[] temperature = new double[7];is like declaring seven variables of type double, namedtemperature[0], temperature[1], temperature[2], temperature[3], temperature[4], temperature[5], temperature[6].

    Similar to:Automobile myCar = new Automobile(Toyota);

  • Creating and Accessing Arrays, cont.These variables can be used just like any other variables of type double.examplestemperature[3] = 32.0;temperature[6] = temperature[3] + 5;System.out.println(temperature[6]);temperature[index] = 66.5;These variables are called indexed variables, elements, or subscripted variables.

  • The length Instance VariableAn array has only one public instance variable, length.The length variable stores the number of elements the array can hold.Using Array_Name.length typically produces clearer code than using an integer literal.length is an instance variable, not a methodArray_Name.length() wont work

  • Indices and lengthThe indices of an array start with 0 and end with Array_Name.length-1.When a for loop is used to step through an array, the loop control variable should start at 0 and end at length-1.examplefor (lcv = 0; lcv < temperature.length; lcv++)

  • Array Index Out of BoundsEvery index must evaluate to an integer which is not less than 0 and not greater than Array_Name.length-1.Otherwise, the index is said to be out of bounds or invalid.An out-of-bounds index will produce a run-time error.

  • Arrays of Objects

  • Entire Arrays as Method ArgumentsAn entire array can be used as a single argument passed to a method.exampledouble[] a = new double[10];SampleClass.change(a);...public static void change(double[] d)No brackets accompany the argument.Method change accepts an array of any size.

  • Methods that Return ArraysA method can return an array.The mechanism is basically the same as for any other returned type.examplepublic static Base_Type[] Method_Name (Parameter_List)Base_Type Array_Name;return Array_Name;The method need not be public or static.

  • Sorting ArraysSometime we want numbers in an array sorted from smallest to largest, or from largest to smallest.Sometimes we want the strings referenced by an array to be in alphabetical order.Sorting techniques typically are easy to adapt to sort any type that can be ordered.

  • Selection SortThe selection sort arranges the values in an an array so thata[0]
  • Selection Sort, cont.Selection sort begins by finding the smallest item in the array and swapping it with the item in a[0].Selection sort continues by finding the smallest item in the remainder of the array and swapping it with the next item in array a.Selection sort terminates when only one item remains.

  • Selection Sort, cont.

  • Swapping ElementsTo swap two elements a[i] and a[j], one of them must be saved temporarily.

  • Swapping Elements, cont.class interchange

  • Introduction to Multidimensional ArraysAn array with more than one index sometimes is useful.example: savings account balances at various interest rates for various numbers of yearscolumns for interest ratesrows for yearsThis two-dimensional table calls for a two-dimensional array.

  • Introduction to Multidimensional Arrays, cont.

  • Introduction to Multidimensional Arrays, cont.

  • Introduction to Multidimensional Arrays, cont.An array with n indices is called an n-dimensional array.The arrays we considered previously, which had one index, were one-dimensional arrays.

  • Multidimensional-Array Basicsexample declarationint[][] table = new int [10][6];orint[][] table;table = new int[10][6];The number of bracket pairs in the declaration is the same as the number of indices.

  • Multidimensional-Array Basics, cont.syntaxBase_Type[][] Array_Name = new Base_Type[Length_1][Length_n];exampleschar[][] page = new char [100][80];double[][][] threeDPicture = new double[10][20][30];SomeClass[][] entry = new SomeClass[100][80];

  • Multidimensional-Array Basics, cont.Nested for loops can be used to change the values of the elements of the array and to display the values of the elements of the array.

  • Multidimensional-Array ParametersMethods may have multidimensional-array parameters.

  • Multidimensional-Array Returned ValuesA method may return a multidimensional array.examplepublic static double[][] corner(double[][] sArray, int i){double[][] temp = new double[i][i];return temp;}

  • Implementation of Multidimensional ArraysMultidimensional arrays are implemented in Java using one-dimensional arrays.Considerint[][] table = new int[10][6];The array table is a one-dimensional array of length 10.Its base type is int[].Therefore, it is an array of arrays.

  • Implementation of Multidimensional Arrays, cont.This permits us to use the length instance variable, instead of an integer literal, to control a for loop used to initialize or print the values of the elements of an array.example for (r = 0; r < table.length; r++) for (c = 0; c < table[r].length; c++)

  • Ragged ArraysSince a two-dimensional array in Java is an array of arrays, each row can have a different number of elements (columns).Arrays in which rows have different numbers of elements are called ragged arrays.

  • Ragged Arrays, cont.Exampleint[][] b = new int[3][];b[0] = new int[5];b[1] = new int[7];b[2] = new int[4];

  • (optional) Graphics Supplement: OutlinePart 1: Text Areas and Text FieldsPart 2: Drawing Polygons and Polylines

  • Text Areas and Text FieldsA text area is a window that can be used for text input and text output.any number of linesany number of characters per lineA text field allows only one line of characters.Text area and text fields provide areas for changeable text in a GUI.

  • Programming Example: A Question and Answer AppletThe applet accepts a question, requests some advice, and provides an answer.The applet contains some advice for the first user, but then takes the advice provided by one user, and uses it to answer the next user.

  • Programming Example:, cont.

  • JTextArea ObjectsA text area is an object of the class JTextArea.A JTextArea can be created withprivate JTextArea theText;theText = new JTextArea(LINES, CHAR_PER_LINE);Typically, this occurs inside the init method.

  • JTextArea Objects, cont.The text in the text area can be read usingString question = theText.getText();The text in the text area can be set usingtheText.setText(Thats difficult.\n +I need some advice.\n +Give me some advice and click.);Text can be entered in excess of the specified size, but may not be entirely visible.

  • JTextField ObjectsA text field is an object of the class JTextField.A JTextField can be created withprivate JTextField theText;theText = new JTextField(NUMBER_OF_CHARS);Typically, this occurs inside the init method.

  • JTextField Objects, cont.The text in the text field can be read usingString question = theText.getText();The text in the text area can be set usingtheText.setText(Thats all, folks.);Text can be entered in excess of the specified size, but may not be entirely visible.

  • Drawing Polygons and PolylinesThe methods drawPolygon and fillPolygon allow you to draw polygons which are closed figures made of of line segments that meet at vertices but do not cross.A polyline is similar to a polygon, but uses the method drawPolyline and need not be closed.

  • Drawing Polygons and Polylines, cont.

  • Drawing Polygons and Polylines, cont.class House

  • Drawing Polygons and Polylines, cont.

  • Method drawPolygonsyntaxcanvas.drawPolygon(Array_of_xs, Array_of_ys, Number_of_Points);exampleprivate int[] xCoord = {150, 150, 200, 250, 250};private int[] yCoord = {100, 40, 20, 40, 100};canvas.drawPolygon(xCoord, yCoord, xCoord.length);

  • Method fillPolygonsyntaxcanvas.fillPolygon(Array_of_xs, Array_of_ys, Number_of_Points);exampleprivate int[] xCoord = {150, 150, 200, 250, 250};private int[] yCoord = {100, 40, 20, 40, 100};canvas.fillPolygon(xCoord, yCoord, xCoord.length);

  • Method drawPolylinesyntaxcanvas.drawPolyline(Array_of_xs, Array_of_ys, Number_of_Points);exampleprivate int[] xCoord = {150, 150, 200, 250, 250};private int[] yCoord = {100, 40, 20, 40, 100};canvas.drawPolyline(xCoord, yCoord, xCoord.length);

  • Method drawPolyline, cont.There is no automatic line segment from the last point to the first point.As a consequence, the figure typically is not closed.A polyline cannot be filled.

  • SummaryYou have learned about arrays and how to use them in Java programs.You have learned how to use array parameters and how to define methods that return an array.You have learned the proper use of an array as an instance variable.You have learned about multidimensional arrays.

  • Summary, cont.(optional) You have learned about text fields and text areas in applets.(optional) You have learned to draw arbitrary polygons and polylines in applets.