Sei sulla pagina 1di 4

1

!"#$%"&' ) *+,-$& ./01 2$-3 4 5673



89$&:+3$ 0; 2+#7<$ #$-="> -" 3"&- 6, 6&&6? "@ 3-&+,A3

6B You can easily soit a stiing aiiay using the sort() methou fiom the Arrays class. Examine
that compile anu iun the following coue.

CB Aujust the coue so the usei can entei names (of animals oi fiienus) at the keyboaiu (using a
while loop) anu then piint out the names in alphabetical oiuei.
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

89$&:+3$ .; Beie is a collection of animals.
{"cat", "cat", "cat", "dog", "cat", "dog", "zebra", "zebra", "pony"}
6B Fiist place them all in an aiiay.

CB Then auu each animal to a 2$- (use an enhanceu foi loop) anu iepoit how many uiffeient kinus
of animals theie aie. This will use the fact that a Set can only holu one of each.

:B 0se the contains() methou to see if the set contains a pony anu piint out the iesult.





2
89$&:+3$ D; 0nion anu Inteisection of Sets (fiom sciatch)
In auuition to youi text, ieview the methous available in the 2$- inteiface uesciibeu heie.
http:uocs.oiacle.comjavase7uocsapijavautilSet.html

6B In auuition to add(), we can use addAll() to auu all the elements of one set oi collection to anothei
set. In geneial you can auu all the elements of one collection to anothei. 0se this methou to finu the
E,+", C of these two sets. Piint out sets A, B anu the union.
Note: The notation below is mathematical set notation, ,"- }ava coue.

A = { "Auam", "Bienua", "Canuy", "Bave", "Eve"} B = { "Auam", "Bienua", "Feiiis", "uuy", "Baiiy"}

CB Finu the +,-$&3$:-+", ! of these two sets. 0se piogiammatic methous.
0se this logic. Cieate an empty set B foi the inteisection. Then auu each element of A to B, if it is also
containeu in B. 0se the contains() methou anu an if( ) { } statement.

0bviously youi coue shoulu piouuce B = {"Auam", "Bienua" } , but you must use the logic pioviueu above
anu not just uiiectly specify the inteisection.

:B uo back anu piint out the size() of both the union anu inteisection.

>B Finu anu piint out the set A - B. This is all the elements in A, that aie FGH in B.
Cleaily this uiffeience set is: { "Canuy", "Bave", "Eve"} , but finu it by using foi loops anu logic.

89$&:+3$ 1; 8<$:-+", The following piogiam uses Naps to tally the iesults in an election. It
ieviews the methous HashSet() and add() methods and the HashMap(),get() anu put()
methous.

The piogiam tallies the following votes:
String[] ballots1 = {"John", "Mary", "John" , "Mary", "Joseph", "Adam", "Mary",
"John"};

a. Compile, then run the program. Study how it works. You should see the following output.

Here is the list of candidates.
[Joseph, Mary, Adam, John]

The election results are:
Joseph -> 1
Mary -> 3
Adam -> 1
John -> 3

The winner of the election is: Mary

b. Unfortunately there is a little problem the election is actually a tie for first place. The method
findWinner() assumes incorrectly that there is always a unique winner. Replace the method with a
new method called findWinners()which returns a set containing all the winners. Use this new
method to print out all the winners.




S
Here is the new header and a line containing the correct constructor.

private static Set<String> findWinners(Map<String,Integer> results )
{ Set<String> winners = new HashSet<String>();

//1.First find just one winner as before.
String winner = null; int votes = 0;
Set<String> keySet = results.keySet();
for (String key : keySet)
{ if (results.get(key) > votes) {votes = results.get(key);
winner = key;}
} // end of for loop

//2.Add a for loop to add each candidate who ties the winner found above to the Set
of winners.


return winners;
} // end of method findWinners




Election.java
import java.util.*;
public class Election {

public static void main(String[] args)
{ Map<String, Integer> electionResults = new
HashMap<String,Integer>();

//0. Here are the ballots from the first precinct.
String[] ballots1 = {"John", "Mary", "John" , "Mary", "Joseph",
"Adam", "Mary", "John"};
HashSet<String> candidates = new HashSet<String>();

int result;
//1. Now create a set containing the name of each person who received at least one
vote.
for(String name : ballots1) {candidates.add(name);}
System.out.println("\nHere is the list of candidates.");
System.out.println(candidates);

//2. Add up the votes for each candidate.
//a.First set each vote count to zero.
for(String name : candidates) { electionResults.put(name, 0); }

//b.Now add up the results.
int temp = 0;
for(String name : ballots1) {
temp = electionResults.get(name);
electionResults.put(name, temp+1);
}

//3. Print out the election results.
System.out.println("\nThe election results are:");
print(electionResults);


4

//4. Find the winner.
System.out.println("\nThe candidates in first place are: " +
findWinner(electionResults) +"\n");

} // end of main method


private static void print(Map<String,Integer> mapToPrint )
{
Set<String> keySet = mapToPrint.keySet();
for (String key : keySet)
System.out.println("\t" + key + " \t-> " +
mapToPrint.get(key) );

} // end of method print

private static String findWinner(Map<String,Integer> results )
{ String winner = null; int votes = 0;
Set<String> keySet = results.keySet();
for (String key : keySet)
{ if (results.get(key) > votes) {votes = results.get(key);
winner = key;}
} // end of for loop
return winner;
} // end of method findWinner

} // end of class

Potrebbero piacerti anche