HELP FOR COMPUTER SCIENCE - CS 141 Part 1: Write a method called mode that has a
ID: 3557140 • 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
Part 1:
Method Code:
public static void mode(int num[])
{
int temp=0;
int[] count = new int[num.length];
Arrays.sort(num);
for(int i=0;i<num.length;i++)
{
for(int j=i+1;j<num.length;j++)
{
if(num[i]==num[j])
count[i]++;
}
}
int large=count[0];
for(int i=0;i<num.length;i++)
{
if(count[i]>large)
large=num[i];
}
System.out.println(""+large);
}
Part 2:
class StringStack
{
String[] stack;
int size;
int top;
public StringStack()
{
size=10;
top=0;
stack=new String[size];
}
public StringStack(int n)
{
if(size<=0)
{
System.err.println("The size must be positive");
System.err.println("Hence creating with size =10");
size=10;
}
else
{
size=n;
top=0;
stack=new String[size];
}
}
public void push(String s) throws StackOverflowException
{
if(isFull())
throw new StackOverflowException();
stack[top]=s;
top++;
}
public String pop() throws StackUnderflowException
{
if(isEmpty())
throw new StackUnderflowException();
top--;
stack[top]=null;
}
public boolean isEmpty()
{
return (top==0);
}
public boolean isFull()
{
return (top==size);
}
public String peek() throws StackUnderflowException
{
if(isEmpty())
throw new StackUnderflowException();
return stack[top-1];
}
public int size()
{
return size;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.