CSIT115 Class 18

Go over midterm exam

Tuesday: Makeup exam, max score 90, in class. So if you got over 90 or near 90, you have a day off.

Start on hw4:

1.        #6, pg. 492

2.        #18, pg. 493

3.        #1, pg. 496

To be continued next week

ArrayLists

See handout for intro to ArrayLists,  Beatles.java.  Competition to bands example in our text.

Programming Problem solved by ArrayList

Consider program to reverse the order of words given in a file: this requires storing the input in memory and then outputting it in reverse order.
input file hamlet.txt, as on pg. 380.

To be or

not to be

java ReverseWords
be to not or be To

We need to read in the words from an input file and hold them in memory until we output them.

If we use an array to hold the words, we need to decide how big it will be. But we really don't know how big to make it. That's where ArrayList comes in: it stretches and stretches to hold any number of objects.

ArrayList<String> words = new ArrayList<String>();  // start with empty ArrayList

 

// in the input loop, like on pg. 380:

  String word = input.next();

  words.add(word); // add word on at end

 

// Later after the input loop, output them in reverse order:

for (int i = words.size()-1; i>=0; i--) {

  System.out.println(words.get(i) + “ “);

}

 

Continue next Thursday.