lab7 - Lab 7 Exercise 1: Simple method to sort an array of...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
Page 1 of 7 Lab 7 Exercise 1: Simple method to sort an array of strings a. You can easily sort a string array using the sort() method from the Arrays class. Examine that compile and run the following code. b. Adjust the code so the user can enter names (of animals or friends) at the keyboard (using a while loop) and then print out the names in alphabetical order. Animals.java import java.util.Arrays; public class Animals { public static void main ( String args [ ] ) { String animals[] = new String[4]; animals[0] = "snake"; animals[1] = "kangaroo"; animals[2] = "wombat"; animals[3] = "bird"; System.out.println("\nHere are the animals in their original order."); for (int i=0; i<4; i++) { System.out.println("animal " + i + " : " + animals[i]); } System.out.println("\nHere are the animals in alphabetical order."); Arrays.sort(animals); for (int i=0; i<4; i++) { System.out.println("animal " + i + " : " + animals[i]); } } // end of main } // end of class
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Page 2 of 7 Exercise 2: Method to sort an array list of strings a. You can sort a string array list using the sort() method from the Collections class. Examine that compile and run the following code. b. Attempt to use Arrays.sort() Document the error message. c. Replace the for loops with "for each" loops. Bugs.java import java.util.ArrayList; import java.util.Collections; public class Bugs { public static void main ( String args [ ] ) { ArrayList<String> insects = new ArrayList<String>(); insects.add("mosquito"); insects.add("butterfly"); insects.add("dragonfly"); insects.add("fly"); System.out.println("\nHere are the bugs in their original order."); int size = insects.size(); for (int i=0; i<size; i++) { System.out.println("insect " + i + " : " + (String) insects.get(i)); } System.out.println("\nHere are the bugs after sorting."); Collections.sort(insects); for (int i=0; i<size; i++) { System.out.println("insect " + i + " : " + (String) insects.get(i)); } } // end of main } // end of class
Background image of page 2
Page 3 of 7 Exercise 3: Method to sort an array of objects. a.
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 09/22/2009 for the course ECEC 301 taught by Professor Carr during the Spring '09 term at Drexel.

Page1 / 7

lab7 - Lab 7 Exercise 1: Simple method to sort an array of...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online