问题描述
我正在尝试编写一个isEmpty()和isFull()方法,以检查堆栈是否为空或其中是否有值。我不确定如何编写方法,以便所有测试均成功返回。这是类和方法的代码:
public class stack {
private int top;
private int maxSize;
private String stackItems[];
//default no-args constructor
public stack() {
this.maxSize = 5;
this.top = -1;
this.stackItems = new String[maxSize];
}
//allows you to set the max size of the stack
public stack(int maxSize) {
this.maxSize = maxSize;
this.top = -1;
this.stackItems = new String[maxSize];
}
//I have two tests for this method: testIsFullFalse and testIsFullTrue
public boolean isFull() {
return top == maxSize -1;
}
//Two tests for this method: testIsEmptyFalse and testIsEmptyTrue
public boolean isEmpty() {
// In progress
return top != maxSize -1;
}
以下是测试:
@Test
void testIsEmptyTrue() {
// ARRANGE
stack myStack = new stack(1);
boolean actual,expected;
// ACT
actual = myStack.isEmpty();
expected = true;
// ASSERT
assertEquals(expected,actual);
}
@Test
void testIsEmptyFalse() throws StackFullException {
// ARRANGE
stack myStack = new stack(1);
String item = "Java is Fun!";
boolean actual,expected;
// ACT
myStack.push(item);
actual = myStack.isEmpty();
expected = false;
// ASSERT
assertEquals(expected,actual);
}
@Test
void testIsFullTrue() throws StackFullException {
// ARRANGE
stack myStack = new stack(1);
String item = "testing";
boolean actual,expected;
// ACT
myStack.push(item);
actual = myStack.isFull();
expected = true;
// ASSERT
assertEquals(expected,actual);
}
@Test
void testIsFullFalse() throws StackFullException {
// ARRANGE
stack myStack = new stack(1);
boolean actual,expected;
// ACT
actual = myStack.isFull();
expected = false;
// ASSERT
assertEquals(expected,actual);
}
现在,testIsEmptyTrue()和testIsFullFalse()返回成功,而testIsEmptyFalse()和testIsFullTrue()返回失败。我希望他们都作为成功回来。关于如何修复方法的任何指示?
解决方法
有点困难,没有看到push方法,但是问题可能出在这里:
//Two tests for this method: testIsEmptyFalse and testIsEmptyTrue
public boolean isEmpty() {
// In progress
return top != maxSize -1;
}
除非isEmpty()
等于top
,否则maxSize -1
方法将始终返回true。
对于名为“ isEmpty”的方法,这样的事情怎么样:
private static final int bottom = -1;
private int top = bottom;
private int maxSize;
private String stackItems[];
//default no-args constructor
public stack() {
this.maxSize = 5;
//this.top = -1;
this.stackItems = new String[maxSize];
}
//allows you to set the max size of the stack
public stack(int maxSize) {
this.maxSize = maxSize;
//this.top = -1;
this.stackItems = new String[maxSize];
}
...
//Two tests for this method: testIsEmptyFalse and testIsEmptyTrue
public boolean isEmpty() {
// In progress
return top == bottom;
}