我需要帮助的事情是:
使 isEmpty() 和 isFull() 方法返回答案以告诉我堆栈是否为空或堆栈是否已满的正确代码是什么
我需要使我正在使用的堆栈大小设置为五(5)(堆栈可以容纳5个整数)
我需要在push()和pop()方法中添加异常,当堆栈已满时不使用push,或者当堆栈为空时使用pop
import java.util.ArrayList;
import java.util.List;
public class IntegerStack {
private List<Integer> stack;
public IntegerStack(int SIZE) {
stack = new ArrayList<Integer>(SIZE);
}
/* method to push the stack */
public void push(int i) {
stack.add(0, i);
}
/* method to pop the stack */
public int pop() {
if (!stack.isEmpty()) {
int i = stack.get(0);
stack.remove(0);
return i;
} else {
return -1;// Or any invalid value
}
}
/* method to peek at the stack */
public int peek() {
if (!stack.isEmpty()) {
return stack.get(0);
} else {
return -1;// Or any invalid value
}
}
/* determine if the stack is empty */
public boolean isEmpty() {
stack.isEmpty();
}
/* determine if the stack is full */
public boolean isFull() {
stack.isFull();
}
/* determine the size of the stack */
public int size() {
if (stack.isEmpty())
return 0;
else
return stack.size();
}
}
1. 正如 Clad 在评论中提到的,看起来您只是缺少 isEmpty() 函数上的
return
关键字:
/* determine if the stack is empty */
public boolean isEmpty() {
return stack.isEmpty();
}
但是,对于
isFull()
函数,isFull()
类上没有 List
函数,您必须自己实现。您必须跟踪通过构造函数传入的整数,以便可以将其与存储在对象中的列表的大小进行比较
2. 您是否应该允许该对象的用户指定他们想要的任何
SIZE
,或者您是否应该始终有 5 个整数限制?
3. 您可能需要阅读 Java 文档中关于 How to Throw Exceptions
的这一部分在提问之前你真的仔细研究过该怎么做吗?好像你只是复制粘贴了一个你没有得到的代码。
import java.util.ArrayList;
import java.util.List;
public class IntegerStack {
private int max_size;
private List<Integer> stack;
public IntegerStack(int size) {
max_size = size;
stack = new ArrayList<Integer>(size);
}
/* method to push the stack */
public void push(int i) {
stack.add(0, i);
}
/* method to pop the stack */
public int pop() {
if (!stack.isEmpty()) {
int i = stack.get(0);
stack.remove(0);
return i;
} else {
return -1;// Or any invalid value
}
}
/* method to peek at the stack */
public int peek() {
if (!stack.isEmpty()) {
return stack.get(0);
} else {
return -1;// Or any invalid value
}
}
/* determine if the stack is empty */
public boolean isEmpty() {
return stack.isEmpty();
}
/* determine if the stack is full */
public boolean isFull() {
//go through all your stack and see if there are things not set to get if it's full.
}
/* determine the size of the stack */
public int size() {
if (stack.isEmpty())
return 0;
else
return stack.size();
}
}
当您创建对象时,您将 5 作为参数。您可能需要对代码进行其他更改;)
自己尝试一下,你会进步更多:D