chapter 6 arrays - plymouth state universityzshen/webfiles/notes/cs237/note6.pdf · chapter 6...

34
Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access and modify data. We will explore more about the ways to group and organize data in a later chapter, and even more in a later course. We now discuss a very simply way to put them together, an array of data. When writing a program to work with, e.g., a list of 100 piece of data, it is not practical to treat them as 100 isolated data. The array structure lets us declare them as a whole. 1

Upload: others

Post on 13-Jul-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

Chapter 6Arrays

We want to organize objects or primitive data

in a form that is easy to access and modify

data. We will explore more about the ways to

group and organize data in a later chapter, and

even more in a later course. We now discuss a

very simply way to put them together, an array

of data.

When writing a program to work with, e.g.,

a list of 100 piece of data, it is not practical

to treat them as 100 isolated data. The array

structure lets us declare them as a whole.

1

Page 2: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

Array indexing

An array is a list of values, each of which isstored at a specific, numbered position in thearray. Those numbers corresponding to posi-tions are referred to as index or subscript. InJava, they start at 0, thus, the data with index5 is actually stored in the sixth position.

To access a value in an array, we use the nameof this array, together with its index. Thus, toget the value with index 5 in an array height,

we use the expression of height[5]. Such anexpression can be used whenever an integercan be used.

Before we use an array, we have to declare it.For example,

int[] height=new int[11];

declares an array, height, with 11 int type el-ements.

2

Page 3: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

More examples

Once the height array is declared, the following

are all valid expressions:

height[2]=72;

height[count]=feet*12;

average=(height[0]+height[1]+height[2])/3;

System.out.println("The middle value is "

+height[MAX/2]);

pick=height[rand.nextInt(11)];

When declaring an array, we don’t need to give

its size. However, once it is instantiated with

the new, its size can’t be changed.

3

Page 4: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

A complete example

The following code shows how to initialize anarray, change one value, then print the wholearray.

public class BasicArray{

final static int LIMIT = 15;

final static int MULTIPLE = 10;

public static void main(String[] args){

int[] list = new int[LIMIT];

//Initialize the array values

for(int index = 0;index<LIMIT;index++)

list[index] = index * MULTIPLE;

list[5] = 999; // change one array value

for (int index=0;index<LIMIT;index++)

System.out.print(list[index]+ " ");

System.out.println ();

}

}

4

Page 5: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

A couple of points

1. Technically, the bracket “[]” is an operator,

and usually, has the highest precedence.

2. The index operator carries out automatic

bound checking. Thus, if you try to print out

height[23], an exception will be thrown back.

3. The size of any array is kept in a public

variable, length, coming with the array.

4. Arrays can also be declared in an alternative

way. For example,

int height[];

Homework: Exercises 6.1, 6.2, 6.3 and 6.4.

5

Page 6: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

Another example

The following code shows how to read in a list

of numbers, then print them out in an reversed

order.

public class ReverseOrder{public static void main (String[] args){double[] numbers = new double[10];System.out.println ("The size of the array: "

+ numbers.length);

for (int index = 0; index < numbers.length; index++){System.out.print("Enter number " + (index+1) + ": ");numbers[index] = Keyboard.readDouble();}

System.out.println("The numbers in reverse order:");

for (int index=numbers.length-1;index>=0;index--)System.out.print(numbers[index] + " ");

System.out.println();}}

6

Page 7: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

A couple of points

1. Arrays can be initialized. For example,

int score=new int[4];

char letterGrades=new char[4];

score={87, 98, 78, 23};

letterGrades={’A’, ’B’, ’C’, ’F’};

2. Array can also be used as parameters. When

an array is passed in, a copy of the reference

to this array as an object is passed in.

An array element can also be passed in. If the

type of its element is a primitive type, a copy

of its value is passed in.

Homework: Exercises 6.5 and 6.6.

7

Page 8: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

Array of string objects

Consider the following line

String[] words=new String[25];

the variable words now becomes an array of

references to String objects. The new operator

instantiates this array and reserves space for

them. An important point is that it does not

create any String objects at this point.

In the following example, an array of String

objects are created, the associated string are

created later, using string literals contained in

the initializing list.

8

Page 9: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

An example

public class GradeRange{public static void main (String[] args){String[] grades = {"A", "A-", "B+", "B", "B-", "C+",

"C", "C-", "D+", "D", "D-", "F"};int[] cutoff={95,90,87,83,80,77,73,70,67,63,60,0};

for (int level = 0; level < cutoff.length; level++)System.out.println(grades[level]+"\t"+cutoff[level]);}

}

The problem with this sort of parallel array is

that they may go out of sync. Thus, a better

way is to construct one array of pairs, contain-

ing both the letter grade and the correspond-

ing cutoff. Such a pair can be done as a class.

Thus, we now will work with an array of ob-

jects, each of which consists of a pair.

9

Page 10: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

Filling arrays of objects

As we have said many times, it takes two sep-

arate steps to create an array and then fill it.

public class Tunes{public static void main (String[] args){CDCollection music = new CDCollection ();

music.addCD ("Storm Front", "Billy Joel", 14.95, 10);music.addCD ("Come On Over", "Shania Twain", 14.95, 16);music.addCD ("Soundtrack", "Les Miserables", 17.95, 33);music.addCD ("Graceland", "Paul Simon", 13.90, 11);

System.out.println (music);

music.addCD ("Double Live", "Garth Brooks", 19.99, 26);music.addCD ("Greatest Hits", "Jimmy Buffet", 15.95, 13);

System.out.println (music);}}

The CDCollection class is defined in the follow-

ing slides.

10

Page 11: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

The CDCollection class

public class CDCollection{private CD[] collection;private int count;private double totalCost;

public CDCollection (){collection = new CD[100];count = 0; totalCost = 0.0;

}

public void addCD (String title, String artist,double cost, int tracks){

if (count == collection.length)increaseSize();

collection[count]=new CD(title,artist,cost,tracks);totalCost += cost;count++;}

11

Page 12: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

public String toString(){NumberFormat fmt = NumberFormat.getCurrencyInstance();String report = "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n";report += "My CD Collection\n\n";

report += "Number of CDs: " + count + "\n";report += "Total cost: " + fmt.format(totalCost) + "\n";report += "Average cost: " + fmt.format(totalCost/count);report += "\n\nCD List:\n\n";

for (int cd = 0; cd < count; cd++)report += collection[cd].toString() + "\n";

return report;}

private void increaseSize (){CD[] temp = new CD[collection.length * 2];

for (int cd = 0; cd < collection.length; cd++)temp[cd] = collection[cd];

collection = temp;}}

12

Page 13: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

Selection sort

Sorting is the process of putting things in or-

der. There are many ways to do sorting. We

begin with a simple way, selection sort, which

sorts things by successively selecting the small-

est data, and putting it into its final place.

public static void selectionSort (int[] numbers){int min, temp;for (int index=0;index<numbers.length-1;index++){min = index;for(int scan=index+1;scan<numbers.length;scan++)if(numbers[scan]<numbers[min]) min = scan;

temp = numbers[min];numbers[min] = numbers[index];numbers[index] = temp;

}}

13

Page 14: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

How to run selection sort?

Below shows how to pass in an array object

to a method, particularly, how to sort a list of

numbers.

public class SortGrades{public static void main (String[] args){int[] grades={89,94,69,80,97,85,73,91,77,85,93};

Sorts.selectionSort(grades);

for (int index = 0; index < grades.length; index++)System.out.print (grades[index] + " ");

}}

14

Page 15: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

Insertion sort

Insertion sort sorts things by inserting each and

every element into the right place. In the fol-

lowing code, it starts with the left end and

moves to the right. For every position, it goes

backwards to insert the current data to its right

place.

public static void insertionSort (int[] numbers){for (int index=1;index<numbers.length;index++){int key = numbers[index];int position = index;

// shift larger values to the rightwhile (position > 0 && numbers[position-1] > key){numbers[position] = numbers[position-1];position--;

}numbers[position] = key;

}}

15

Page 16: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

The general insertion sort

The key difference between this more generalinsertion sort and the previous one is that nowwe apply it to a list of comparable objects,namely, the data within need not be int, aslong as they are comparable. The class for thatobject has to implement the Comparable class,and more specifically, the compareTo methoddefinition will tell us the order between any twoobjects in that class.

public static void insertionSort(Comparable[] objects){for (int index=1; index<objects.length; index++){Comparable key = objects[index];int position = index;while (position > 0 &&

objects[position-1].compareTo(key)>0){objects[position] = objects[position-1];position--;

}objects[position] = key;

}}

Homework: Read the relevant part in pp. 346and pp. 349.

16

Page 17: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

Sort comparison

There could be a few reasons to pick one sort-ing method over another one, such as its sim-plicity, the level of efficiency, the amount ofspace it needs, the amount of time it takes,etc..

Both insertion sort and selection sort basicallytake the same amount of space and time torun. More specifically, the time need for bothis O(n2), in the sense that both will take timeproportional to n2, where n is the size of thelist. But, insertion sort is faster when the listis close to be sorted, while selection sort al-

ways take the same amount of work, no matterwhat.

On the other hand, selection sort is easier tounderstand, and will often suffice in lots ofcases. We will further study the difference be-

tween algorithms in a later course.

17

Page 18: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

Two-dimensional arrays

We have so far only looked at the one-dimensional

arrays representing simple list of values. As a

straightforward extension, the two-dimensional

arrays represent a collection of values in two di-

mensions, or looked at from another angle, a

list of pairs.

18

Page 19: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

Declaration, etc.

When declaring it, we now have to use two

sets of brackets. For example,

int [][] table;

In accessing a value in such an array, we also

have to give two indices to identify it, one for

the row, and the other for the column.

By the same token, we can declare multi-dimensional

arrays, which can be used, e.g., to represent

the number of students attending colleges across

USA, we could use a 4D array.

19

Page 20: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

An example

The following piece of code declares and cre-

ates a 2D array, fills it with increasing integers,

then prints them out.

public class TwoDArray{public static void main(String[] args){int[][] table=new int[5][10];for (int row=0; row<table.length; row++)for (int col=0; col<table[row].length; col++)

table[row][col] = row * 10 + col;

for (int row=0; row < table.length; row++){for (int col=0; col < table[row].length; col++)

System.out.print (table[row][col] + "\t");System.out.println();

}}}

Question: What should the output look like?

20

Page 21: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

Polygons and polylines

Arrays are helpful when drawing complex shapes.

A polygon is a multi-sided shape that is defined

in Java using a series (list) of (x, y) points that

indicate the vertices of the polygon. An array

is certainly very appropriate to represent such

a list of pairs.

Technically, a polygon is drawn, filled or un-

filled, using methods of the Graphics class, just

like what we did with rectangles and ovals.

Those specific methods are called drawPolygon

and fillPolygon, respectively. Each of them

takes three parameters, the list of x coordi-

nates, that for the associated y, and the num-

ber of points, i.e., the size of those two lists.

Finally, there is always a line drawn between

the first and the last point.

21

Page 22: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

A polyline is similar to the polygon as a series

of segments represented with a series of points.

But, the segment between the first and the

last point is not automatically drawn. It is not

closed, thus can’t be filled. There is hence

only one method, drawPolyline, which takes

the same parameters as the drawPolygon does.

The next slide shows an applet that draws a

rocket, and its window. The first point in the

array represents the tip of the rocket, the rest

just goes clockwise from the tip. Both poly-

gons are filled.

22

Page 23: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

A rocket with a window

import javax.swing.JApplet;import java.awt.*;public class Rocket extends JApplet{private final int APPLET_WIDTH = 200;private final int APPLET_HEIGHT = 200;private int[] xRocket={100,120,120,130,130,70,70,80,80};private int[] yRocket={15,40,115,125,150,150,125,115,40};private int[] xWindow={95,105,110,90};private int[] yWindow={45,45,70,70};private int[] xFlame={70,70,75,80,90,100,110,

115,120,130,130};private int[] yFlame={155,170,165,190,170,175,

160,185,160,175,155};public void init(){setBackground (Color.black);setSize (APPLET_WIDTH, APPLET_HEIGHT);

}public void paint (Graphics page){page.setColor (Color.cyan);page.fillPolygon (xRocket, yRocket, xRocket.length);page.setColor (Color.gray);page.fillPolygon (xWindow, yWindow, xWindow.length);page.setColor (Color.red);page.drawPolyline (xFlame, yFlame, xFlame.length);

}}

23

Page 24: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

More buttons

We have so far discussed the push button com-ponent: once pushed, an action event is gen-erated, which we can respond with a listener.Let’s check out some other buttons.

A check box is a button that can be toggled onor off using the mouse, indicating that a par-ticular boolean condition is set or unset. Forexample, a check box labeled Collate can beused to indicate whether the output of a printjob should be collated.

If there are multiple check boxes created inyour program, all of them are independent ofeach other.

24

Page 25: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

Simple font changer

The following piece changes the font of the

text displayed in a text field.

import javax.swing.*;

public class StyleOptions{public static void main (String[] args){JFrame styleFrame = new JFrame ("Style Options");styleFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);StyleGUI gui = new StyleGUI();styleFrame.getContentPane().add(gui.getPanel());styleFrame.pack();styleFrame.show();

}}

The StyleGUI class is given in the next slide.

25

Page 26: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

The StyleGUI class

import javax.swing.*;import java.awt.*;import java.awt.event.*;

public class StyleGUI{private final int WIDTH=300,HEIGHT=100,FONT_SIZE=36;private JLabel saying;private JCheckBox bold, italic;private JPanel primary;public StyleGUI(){saying = new JLabel ("Say it with style!");saying.setFont(new Font("Helvetica",Font.PLAIN,FONT_SIZE));bold = new JCheckBox ("Bold");bold.setBackground (Color.cyan);italic = new JCheckBox ("Italic");italic.setBackground (Color.cyan);StyleListener listener = new StyleListener();bold.addItemListener (listener);italic.addItemListener (listener);primary = new JPanel();primary.add (saying);primary.add (bold);primary.add (italic);primary.setBackground(Color.cyan);primary.setPreferredSize(new Dimension(WIDTH,HEIGHT));

}

26

Page 27: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

The StyleGUI class (Con’d)

public JPanel getPanel(){return primary;}

private class StyleListener implements ItemListener{public void itemStateChanged (ItemEvent event){int style = Font.PLAIN;if (bold.isSelected())

style = Font.BOLD;if (italic.isSelected())

style += Font.ITALIC;saying.setFont(new Font("Helvetica",style,FONT_SIZE));

}}

In this program, we also use the Font class,

part of the Java standard library. A Font object

is defined by the font name, the font style,

and the font size. The name established the

basic characteristic of the characters, such as

Times, Helvetica, etc.. The style of a Java

font can be plain, bold, italic, or bold and

italic combined. The size simply decides how

big the characters will look like.

27

Page 28: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

Radio buttons

A radio button is used with other radio buttons

to provide a set of mutually exclusive options.

Thus, unlike the check box, it is not mean-

ingful by itself, and has to be used with other

radio buttons.

Only one option among that group is valid.

In other words, at any time, exactly one ra-

dio button is on, and the rest is automatically

toggle off.

28

Page 29: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

Which quote do you like?

The following piece of code displays a label and

a set of associated radio buttons. The radio

button decides which quote is to be displayed

in the label.

Question: What do we have to use radio but-

ton, but not a check box, in this case?

Answer: Since we only want to put one quote

up there. If we use check box, multiple quotes

can be put there, just like multiple fonts can

be added in the previous case.

29

Page 30: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

Which quote do you like?

The structure of the following is the same asthat for the StyleOptions.

import javax.swing.*;

public class QuoteOptions{public static void main (String[] args){JFrame quoteFrame = new JFrame ("Quote Options");quoteFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

QuoteGUI gui = new QuoteGUI();quoteFrame.getContentPane().add (gui.getPanel());

quoteFrame.pack();quoteFrame.show();

}}

30

Page 31: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

The QuoteGUI classpublic class QuoteGUI{private final int WIDTH = 300, HEIGHT = 100;private JPanel primary;private JLabel quote;private JRadioButton comedy,philosophy,carpentry;private String comedyQuote="Take my wife,please.";private String philosophyQuote="I think,therefore I am.";private String carpentryQuote="Measure twice.Cut once.";public QuoteGUI(){quote = new JLabel (comedyQuote);quote.setFont(new Font("Helvetica",Font.BOLD,24));comedy = new JRadioButton ("Comedy", true);comedy.setBackground (Color.green);philosophy = new JRadioButton ("Philosophy");philosophy.setBackground (Color.green);carpentry = new JRadioButton ("Carpentry");carpentry.setBackground (Color.green);ButtonGroup group=new ButtonGroup();group.add (comedy); group.add (philosophy);group.add (carpentry);QuoteListener listener = new QuoteListener();comedy.addActionListener (listener);philosophy.addActionListener (listener);carpentry.addActionListener (listener);primary = new JPanel(); primary.add (quote);primary.add (comedy); primary.add (philosophy);primary.add (carpentry);primary.setBackground (Color.green);primary.setPreferredSize(new Dimension(WIDTH,HEIGHT));

}}

31

Page 32: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

The QuoteGUI class (Con’d)

public JPanel getPanel(){return primary;

}

private class QuoteListener implements ActionListener{public void actionPerformed (ActionEvent event){Object source = event.getSource();if (source == comedy)quote.setText (comedyQuote);

else if (source == philosophy)quote.setText (philosophyQuote);

else quote.setText (carpentryQuote);}

}

32

Page 33: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

A couple of points

1. Check box and radio button, unlike push

button, are toggle buttons, namely, either on

or off. But, check boxes are independent of

each other; while radio buttons work in a group,

only one of them is on and the rest is off.

2. A button group is simply a way to define a

group of buttons that will work together, thus,

besides adding in, logically, into this group; all

the buttons also have to be added physically

into a panel to be displayed.

33

Page 34: Chapter 6 Arrays - Plymouth State Universityzshen/Webfiles/notes/CS237/note6.pdf · Chapter 6 Arrays We want to organize objects or primitive data in a form that is easy to access

3. A radio button produces an action event

when it is selected. The actionPerformed method

of the listener firstly determines the source of

the event using the getSource method, and

then compares it with the three radio button

objects, before takes appropriate actions.

Question: Why do we use “==” to compare

source and the objects?

Answer: The comparator “==” compares for

references, thus truly identifies the source of

the action.

Homework: Exercise 6.8.

34