Question
This is in java. Directed Lab Work Counting Game Pieces of the CountingGame class already exist and are in CountingGame.java . Take a look at
This is in java.
Directed Lab Work
Counting Game
Pieces of the CountingGame class already exist and are in CountingGame.java. Take a look at that code
now if you have not done so already. Also before you start, make sure you are familiar with the methods
available to you in the AList class (check ListInterface.html).
Step 1. Compile the classes CountingGame and AList. Run the main method in CountingGame.
Checkpoint: If all has gone well, the program will run and accept input. It will then generate a null pointer
exception. The goal now is to create the list of players.
Step 2. Create a new Alist
Step 3. Using a loop, add new objects of type Integer to the players list.
Checkpoint: Compile and run the program. Enter 3 for the number of players. The program should print out
{ <1> <2> <3> } for the players list. The next goal is to do one round of the game. It will be encapsulated in
the method doRhyme().
Step 4. Complete the doRhyme() method. Use the following algorithm.
For each word in the rhyme
Print the word in the rhyme and the player that says it.
Print the name of the player to be removed.
Remove that player from the list.
Return the index of the player that will start the next round.
Step 5. Call doRhyme(players, rhyme, position) in main after the call to getRhyme().
Step 6. Print out the new player list.
Checkpoint: Compile and run the program. Enter 6 for the number of players. Enter A B C for the rhyme. It
should print out something similar to
Player 1: A
Player 2: B
Player 3: C
Removing player 3
The players list is { <1> <2> <4>< 5> <6> }
Enter 5 for the number of players. Enter A B C D E F for the rhyme. Compare your result with your answers in
the pre-lab. Reconcile any differences. The final goal is to do multiple rounds.
Step 7. Wrap the lines of code from the previous two steps in a while loop that continues as long as there
is more than one player left.
Final checkpoint: Compile and run the program. Enter 6 for the number of players. Enter A B C for the rhyme.
The players should be removed in the order 3, 6, 4, 2, 5. The winner should be player 1.
Enter 5 for the number of players. Enter A B C D E F for the rhyme. Compare your result with your answers in
the pre-lab exercises. Reconcile any differences.
Primes
The skeleton of the Primes class already exists and is in Primes.java.
Step 1. Look at the skeleton in Primes.java. Compile Primes. Run the main method in Primes.
Checkpoint: If all has gone well, the program will run and accept input. It will then end. The goal now is to
create the list of candidates.
Step 2. In main declare and create the candidates list. Add in the values.
Step 3. Print out the candidates list.
Checkpoint: Compile and run the program. Enter 7 for the maximum value. You should see the list { <2>
<3> <4> <5> <6> <7> }. The next goal is to do a single round finding a prime in the candidates list.
Step 4. In main declare and create the primes and composites lists.
Step 5. Remove the first value from the primes list and remember it in a variable.
Step 6. Print out the prime that was discovered.
Step 7. Add it to the primes list.
Step 8. Print out all three lists.
Checkpoint: Compile and run the program. Enter 7 for the maximum value. The value 2 should be removed
from the candidates list and added to the primes. Now all values that are divisible by the prime should be
removed from the candidates list and added to the composites list. Next, this procedure will be encapsulated in
the method getComposites().
Step 9. Refer to the pre-lab exercises and complete the getComposites() method. To determine if one
integer value is divisible by another, you can use the modulus operator (% in Java).
Step 10. Between the code from steps 7 and 8, call getComposites().
Checkpoint: Compile and run the program. Enter 15 for the maximum value. Compare the results with the
pre-lab exercises. Reconcile any differences.
Just as in the counting game, a loop will be used to do the rounds.
Step 11. Wrap the code from steps 5 through 8 in a while loop that continues as long as the candidates list
is not empty.
Final checkpoint: Compile and run the program. Enter 15 for the maximum value. Compare the results with
the pre-lab exercises. Reconcile any differences.
Run the program with 100 as the maximum value. Carefully verify your results.
\
\
\
\
AList class import java.util.Arrays;
/** A class that implements a list of objects by using an array. * Entries in a list have positions that begin with. * Duplicate entries are allowed. * The size of the array doubles until it exceeds the maximum allowed * capacity, where upon an exception is thrown. * * This code is from Chapter 13 of * Data Structures and Abstractions with Java 4/e * @author Frank M. Carrano * * The toString method is overwritten to give a nice display of the items in * the list in this format { <1> <2> <3> <4> } * Modification by Charles Hoot */ class AList
private T[] list; //Array of list entries; ignore list[0] private int numberOfEntries; // current number of entries in list private boolean initialized = false; private static final int DEFAULT_CAPACITY = 25; private static final int MAX_CAPACITY = 10000;
public AList() { this(DEFAULT_CAPACITY); // Call next constructor } // end default constructor
public AList(int initialCapacity) { // Is initialCapacity too small? if (initialCapacity < DEFAULT_CAPACITY) initialCapacity = DEFAULT_CAPACITY; else // Is initialCapacity too big? checkCapacity(initialCapacity); // The cast is safe because the new array contains null entries @SuppressWarnings("unchecked") T[] tempList = (T[]) new Object[initialCapacity + 1]; list = tempList; numberOfEntries = 0; initialized = true; } // end constructor
/** Throws an exception if this object is not initialized. * */ private void checkInitialization(){ if (!initialized) throw new SecurityException("ArrayBag object is not initialized " + "properly."); } // end checkInitialization
/** Throws an exception if the desired capacity exceeds the maximum. * */ private void checkCapacity(int desiredCapacity){ if(desiredCapacity > MAX_CAPACITY) throw new IllegalStateException("Attempt to create a bag " + "whose capacity exceeds " + "allowed maximum."); } // end checkCapacity public void add(T newEntry) { checkInitialization(); list[numberOfEntries+1] = newEntry; numberOfEntries++; ensureCapacity(); } // end add
// Precondition: The array list has room for another entry public void add(int newPosition, T newEntry) { checkInitialization();
if ((newPosition> = 1) && (newPosition <= numberOfEntries + 1)) { if (newPosition <= numberOfEntries) { makeRoom(newPosition); }
list[newPosition] = newEntry; numberOfEntries++; ensureCapacity(); // Ensure enough room for next add } else { throw new IndexOutOfBoundsException("Illegal position given to add operation."); } } // end add
public T remove(int givenPosition) { checkInitialization(); if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) { assert !isEmpty(); T result = list[givenPosition ]; // Get entry to be removed // Move subsequent entries toward entry to be removed, // unless it is last in list if (givenPosition < numberOfEntries) { removeGap(givenPosition); } numberOfEntries--; return result; // Return reference to removed entry } else throw new IndexOutOfBoundsException("Illegal position given to remove operation.");
} // end remove
public void clear() { numberOfEntries = 0; } // end clear
public T replace(int givenPosition, T newEntry) { checkInitialization();
if ((givenPosition> = 1) && (givenPosition <= numberOfEntries)) { assert !isEmpty(); T originalEntry = list[givenPosition]; list[givenPosition] = newEntry; return originalEntry; } else throw new IndexOutOfBoundsException("Illegal position given to replace operation."); } // end replace
public T getEntry(int givenPosition) { checkInitialization(); if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) { assert !isEmpty(); return list[givenPosition]; } else throw new IndexOutOfBoundsException("Illegal position give to getEntry operation."); } // end getEntry
public boolean contains(T anEntry) { checkInitialization(); boolean found = false; int index = 1;
while (!found&& (index <= numberOfEntries)) { if (anEntry.equals(list[index])) { found = true; } index++; } // end for
return found; } // end contains
public int getLength() { return numberOfEntries; } // end getLength
public boolean isEmpty() { return numberOfEntries == 0; } // end isEmpty
public T[] toArray() { checkInitialization(); // the cast is safe because the new array contains null entries @SuppressWarnings("unchecked") T[] result = (T[]) new Object[numberOfEntries];
for (int index = 0; index < numberOfEntries; index++) { result[index] = list[index+1]; } // end for
return result; } // end toArray
// Doubles the size of the array list if it is full. private void ensureCapacity() { int capacity = list.length - 1; if (numberOfEntries> = capacity) { int newCapacity = 2 * capacity; checkCapacity(newCapacity); // Is capacity too big? list = Arrays.copyOf(list, newCapacity + 1); } } // end ensureCapacity
/** Makes room for a new entry at newPosition. * Precondition: 1 <= newPosition <= numberOfEntries+1; * numberOfEntries is list's length before addition. * checkInitialization has been called. */ private void makeRoom(int newPosition) { assert (newPosition> = 1) && (newPosition <= numberOfEntries + 1); int newIndex = newPosition; int lastIndex = numberOfEntries; // Move each entry to next higher index, starting at end of // array and continuing until the entry at newIndex is moved for (int index = lastIndex; index >= newIndex; index--) { list[index + 1] = list[index]; } } // end makeRoom
/** Shifts entries that are beyond the entry to be removed * to the next lower position. * Precondition: 1 <= givenPosition < numberOfEntries; * numberOfEntries is list's length before removal. * checkInitialization has been called. */ private void removeGap(int givenPosition) { assert (givenPosition> = 1) && (givenPosition < numberOfEntries);
int removedIndex = givenPosition; int lastIndex = numberOfEntries; for (int index = removedIndex; index < lastIndex; index++) list[index] = list[index + 1]; } // end removeGap
/** Build a string representation of the list * * @return A string showing the state of the list. */ public String toString() { String result = "{ "; for (int i = 0; i < numberOfEntries; i++) { result = result + "<" + list[i+1] + "> "; } result = result + "}";
return result; } }
\
\
\
\
CountingGame class
import java.io.*; import java.util.*;
/** * CountingGame is a program that will simulate a children's counting game used to select * someone. * * @author Charles Hoot * @version 4.0 */ public class CountingGame {
public static void main(String args[]) { ListInterface
// ADD CODE HERE TO PLAY THE GAME System.out.println("The winner is " + players.getEntry(1)); } /** * Do the rhyme with the players in the list and remove the selected * player. * * @param players A list holding the players. * @param rhyme A list holding the words of the rhyme. * @param startAt A position to start the rhyme at. * * @return The position of the player eliminated. */ public static int doRhyme(ListInterface
} /** * Get an integer value. * * @return An integer. */ private static int getInt(String rangePrompt) { Scanner input; int result = 10; //Default value is 10 try { input = new Scanner(System.in); System.out.println(rangePrompt); result = input.nextInt(); } catch(NumberFormatException e) { System.out.println("Could not convert input to an integer"); System.out.println(e.getMessage()); System.out.println("Will use 10 as the default value"); } catch(Exception e) { System.out.println("There was an error with System.in"); System.out.println(e.getMessage()); System.out.println("Will use 10 as the default value"); } return result; } /** * getRhyme - Get the rhyme. * * @return A list of words that is the rhyme. */ private static ListInterface
// Make sure there is at least one word in the rhyme if(rhyme.getLength()< 1) rhyme.add("Default"); return (ListInterface
\
\
\
\
Primes class
import java.io.*; import java.util.*;
/** * Primes is a program that will compute prime numbers using the sieve of Eratosthenes. * * @author Charles Hoot * @version 4.0 */
public class Primes {
public static void main(String args[]) {
int max; System.out.println("Please enter the maximum value to test for primality"); max = getInt(" It should be an integer value greater than or equal to 2."); // COMPLETE THE MAIN } /** * getComposites - Remove the composite values from possibles list and * put them in the composites list. * * @param candidates A list of integers holding the possible values. * @param composites A list of integers holding the composite values. * @param prime An Integer that is prime. */ public static void getComposites(ListInterface
\
\
\
\
ListInterface class
/** An interface for the ADT list. * Entries in the list have positions that begin with 1. * * This code is from Chapter 12 of * Data Structures and Abstractions with Java 4/e * by Carrano */
public interface ListInterface
/** Adds a new entry at a specified position within this list. * Entries originally at and above the specified position * are at the next higher position within the list. * The list's size is increased by 1. * @param newPosition An integer that specifies the desired * position of the new entry. * @param newEntry The object to be added as a new entry. * @throws IndexOutOfBoundsException if either * newPosition less than 1, or * newPosition greater than getLength()+1. */ public void add(int newPosition, T newEntry);
/** Removes the entry at a given position from this list. * Entries originally at positions higher than the given * position are at the next lower position within the list, * and the list's size is decreased by 1. * @param givenPosition An integer that indicates the position of * the entry to be removed. * @return A reference to the removed entry. * @throws IndexOutOfBoundsException if either * givenPosition less than 1, or * givenPosition greater than getLength()+1. */ public T remove(int givenPosition);
/** Removes all entries from this list. */ public void clear();
/** Replaces the entry at a given position in this list. * @param givenPosition An integer that indicates the position of the * entry to be replaced. * @param newEntry The object that will replace the entry at the * position givenPosition. * @return The original entry that was replaced. * @throws IndexOutOfBoundsException if either * givenPosition less than 1, or * givenPosition greater than getLength()+1. */ public T replace(int givenPosition, T newEntry);
/** Retrieves the entry at a given position in this list. * @param givenPosition An integer that indicates the position of * the desired entry. * @return A reference to the indicated entry. * @throws IndexOutOfBoundsException if either * givenPosition less than 1, or * givenPosition greater than getLength()+1. */ public T getEntry(int givenPosition);
/** Sees whether this list contains a given entry. * @param anEntry The object that is the desired entry. * @return True if the list contains anEntry, or false if not. */ public boolean contains(T anEntry);
/** Gets the length of this list. * @return The integer number of entries currently in the list. */ public int getLength();
/** Sees whether this list is empty. * @return True if the list is empty, or false if not. */ public boolean isEmpty();
/** Retrieves all entries that are in this list in the order in which they occur in the list. @return A newly allocated array of all the entries in the list. */ public T[] toArray(); } // end ListInterface
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started