Java Part 1: Write a complete method at the client level called countMultipleOf.
ID: 3599157 • Letter: J
Question
Java
Part 1:
Write a complete method at the client level called countMultipleOf.
The method counts how many items in a bag are multiples of some number.
For example, if a bag contains (8, 9, 6, 3, 8, 6, 1) and you invoke the method with number = 3, the method will return 4 because there are 4 numbers that are multiples of 3 in the bag (the 9, 6, 3, and 6).
The bag should not be altered when the method completes.
The method header is:
public int countMultipleOf(BagInterface bag, int number)
For this question, you are writing code at the client level. This means you do not know how the bag is implemented.
Use any of the following BagInterface methods to answer the question below.
Note that toArray is not listed and should not be used in your solution.
public boolean add(T newEntry)
public boolean isEmpty()
public boolean contains(T anObject)
public T remove()
public boolean remove(T anEntry)
public int getFrequencyOf(T anEntry)
public int getCurrentSize()
public void clear()
Part 2:
Write a complete method at the client level called countGreaterThan.
The method determines how many numbers on a list are greater than some number.
The list should not be altered by the method.
The method header is:
public int countGreaterThan(ListInterface<Integer> list, int number)
For this question, you are writing code at the client level. This means you do not know how the list is implemented.
Use any of the following ListInterface methods to answer the question below.
Note that toArray is not listed and should not be used in your solution.
public void add(T newEntry)
public void add(int newPosition, T newEntry)
public boolean isEmpty()
public boolean contains(T anObject)
public T remove(int givenPosition)
public T replace(int givenPosition, T newEntry)
public T getEntry(int givenPosition)
public int getLength()
public void clear()
Explanation / Answer
Please find my implementation.
Part 1:
public int countMultipleOf(BagInterface<Integer> bag, int number) {
int count = 0;
while(!bag.isEmpty()) {
int x = bag.remove();
if(x%number == 0)
count++;
}
return count;
}
Part 2:
public int countGreaterThan(ListInterface<Integer> list, int number) {
int count = 0;
for(int i=0; i<list.getLength(); i++) {
if(list.getEntry(i) > number)
count++;
}
return count;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.