{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

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

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

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

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

View Full Document
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
Page 3 of 7 Exercise 3: Method to sort an array of objects.

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}