Issue
So our homework was to implement a stack on our won and then write test cases for it. This is the stack:
import java.util.Vector;
class Stack<T> extends Vector<T> {
private Vector<T> stack;
Stack() {
stack = new Vector<T>();
}
// returns false or true, given the stack is empty or not.
public boolean isEmpty() {
return stack.size() == 0;
}
//returns the top element of the stack without removing it.
public T peek() {
return stack.get(stack.size()-1);
}
//puts a new element to the top of the stack
public void push(T element) {
stack.add(element);
}
//returns and removes the top element of the stack
public T pop() {
return stack.get(stack.size()-1);
}
}
And this is my test class so far.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class StackTest {
@Test
void isEmpty() {
stack s = new stack<Integer>;
assertEquals(true, s.isEmpty());
}
@Test
void peek() {
Stack t = new Stack(1);
}
@Test
void push() {
}
@Test
void pop() {
}
}
I am really having trouble figuring out what is wrong with the first two test methods. Does anybody else have an idea?
Solution
This is wrong:
//returns and removes the top element of the stack
public T pop() {
return stack.get(stack.size()-1);
}
You don't remove the element, use remove instead of get
Other errors:
void isEmpty() {
//Typo errors here, s is uppercase and missing parenthesis
stack s = new stack<Integer>;
assertEquals(true, s.isEmpty());
}
@Test
void peek() {
//What does Stack(1) mean? There is no such constructor in class
Stack t = new Stack(1);
}
Also:
//If you already extend Vector you don't need a Vector field for the data
class Stack<T> extends Vector<T> {
private Vector<T> stack;
Answered By - Rocco
Answer Checked By - Terry (JavaFixing Volunteer)