Lab #10: Splitting Gifts Among Children

The goal of this lab is to write a class SplitGifts for determining how to split birthday party gifts among children. There are three children, twins Duey and Louie and they older brother Huey. The program receives from the user the name of each gift collected and counts how many times the same gift appears. None of the party gifts are subdividable, such as unlike a box of six potato chip bags - in this particular case, the user may enter "potato chip" six times. After receiving all the gifts by their name, the program determines the share of the gifts as follows: if a gift appears an odd number times, Huey gets one (he will thus take away all the gifts that appear just once). The remaining gifts are evenly split between the twins with each getting exactly one half of each remaining gift. For example if there are three boomerangs, one yo-yo, and four playing card sets, each twin gets one boomerang and two sets of playing cards and Huey gets one boomerang and one yo-yo.

The program uses a one-dimensional array of Strings as the name list and an accompanying one-dimensional array of integers. Both are nitialized as length. Upon receiving a name from the user, the program searches in the name array for this new name. If the name already appears in the array, the program adds one to the element of the integer array at the position of occurrence of the name. Otherwise, the program expands both arrays by one element and stores the new name in the last element of the updated String array and 1 in the last element of the integer array. The names are entered using nextLine method of a Scanner built from System.in, so as to allow names containing white spaces. Enter the empty name means the end of list. Ater quitting the loop, the program announces the shares.

Here is the execution of the code:

% java SplitGift
Enter the name of a gift (“” to quit):
Boomerang
Enter the name of a gift (“” to quit):
Yo-yo
Enter the name of a gift (“” to quit):
Yo-yo
Enter the name of a gift (“” to quit):
Snow White DVD
Enter the name of a gift (“” to quit):
Snow White DVD
Enter the name of a gift (“” to quit):
Yo-yo
Enter the name of a gift (“” to quit):

Duey and Louie will each get 1 Yo-yo.
Duey and Louie will each get 1 Snow White DVD.
Huey will get Boomerang.
Huey will get Yo-yo.

Write a method search that looks for a match of a String key in a String[] names. It should return the position of the first occurrence of key in the array. It key does not appear, it should return -1.

You may use this template: SplitGifts.java

Go back to the lab main page

Go back to the home page