HELP FOR COMPUTER SCIENCE - CS 141 Part 1: Write a method called mode that has a
ID: 3557141 • Letter: H
Question
HELP FOR COMPUTER SCIENCE - CS 141
Part 1: Write a method called mode that has a void return type, takes an array of ints as a parameter and prints out the mode of the array. If there is a tie, it should print out all the values that tie for being the mode.
Part 2: Write a class called StringStack that will implement a stack of strings. It should have the following methods:
public StringStack() // constructor that makes a StringStack with an initial capacity of 10
public StringStack(int n) // constructor that makes a StringStack with an initial capacity of n
public void push(String s) // stores the given value at the top of the stack - if this would exceed the current capacity of the stack, you will need to double its capacity
public String pop() // removes and returns the value at the top of the stack - if the stack is empty, this should throw an IllegalStateException
public boolean isEmpty() // returns true if the stack is empty
public String peek() // returns the value at the top of the stack without removing it - if the stack is empty, this should throw an IllegalStateException
public int size() // returns the number of values stored in the stack
Remember -
- Use the exact same method names that I specified.
- Include at least a comment before every method describing the purpose of that method.
- Use appropriate indentation, and make sure that the way you submit your project doesn't get rid of the indentation.
Explanation / Answer
1:
public static int mode(int[] a)
{
int count = 1;
int maxCount = 1;
int modeValue = a[0];
for (int i = 0; i < a.length - 1; i++)
{
if (a[i] == a[i + 1])
{
count++;
if (count > maxCount)
{
modeValue = a[i];
maxCount = count;
}
}
else
{
count = 1;
}
}
return modeValue;
}
2:
import java.util.*;
class StringStack<E> implements StackInterface<E>
{
private ArrayList<E> items;
public StringStack() // default constructor; creates an empty stack
{
items = new ArrayList<E>(10); // initial capacity is 10
}
public StringStack(int n)
{
//one argument constructor, creates a stack with initial capacity initialCapacity
items = new ArrayList<E>(n);
}
public void push(E x)
{
items.add(x); //uses the ArrayList method add(E o)
}
public E pop()
{
if (empty()) // determine whether or not there is an item to remove
return null;
return items.remove(items.size()-1); //uses the ArrayList method remove(int n)
}
public boolean empty()
{
return items.isEmpty();//uses the ArrayList method isEmpty()
}
public int size()
{
return items.size(); //uses the ArayList method size()
}
public E peek()
{
if (empty()) // determine whether or not there is an item on the stack
return null;
return items.get(items.size()-1); //uses the ArrayList method get(int i)
}
}
Please rate me. Thanks a lot.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.