我正在制定一项计划,帮助学生按顺序学习所有校长。我正在使用堆栈。我想按顺序创建一个包含所有总统的堆栈。然后,用户将输入总裁名称,程序将比较输入与堆栈顶部。
我想知道是否有一种方法可以在不使用.push方法的情况下使用Strings填充我的堆栈44次?
以下是我到目前为止的主要内容:
package namepresidents;
import java.util.Scanner;
public class NamePresidents {
public static void main(String[] args)
{
BoundedStackInterface<String> presidents;
presidents = new ArrayStack<String>(41);
presidents.push("George Washington");
String menu = "Would you like to study: \n"
+ "1. All the presidents \n"
+ "2. The first half \n"
+ "3. The second half \n"
+ "0. Exit \n";
Scanner in = new Scanner(System.in);
int option = in.nextInt();
}
}
这是我的ArrayStack类,用于引用:
package namepresidents;
public class ArrayStack<T> implements BoundedStackInterface<T> {
protected final int DEFCAP= 43;
protected T[] stack; //holds stack of elemets
protected int topIndex = -1;
public ArrayStack(){ // default constructor
stack = (T[]) new Object[DEFCAP];
}
public ArrayStack(int maxSize){ // constructor with user defined array size
stack = (T[]) new Object[maxSize];
}
public void push(T element){
//throws excption if the stack is full
//otherwise places element on top of stack
if (!isFull())
{
topIndex++;
stack[topIndex] = element;
}
else
{
throw new StackOverflowException("Push attempted on a full stack.");
}
}
public boolean isFull(){
//returns true if the stack is full
if (topIndex == stack.length-1)
{
return true;
}
else
{
return false;
}
}
public boolean isEmpty(){
//returns true if the stack is empty
if (topIndex == -1)
{
return true;
}
else
{
return false;
}
}
public void pop(){
//throws excption if the stack is full
//otherwise places element on top of stack
if (!isEmpty())
{
stack[topIndex] = null;
topIndex--;
}
else
{
throw new StackUnderflowException("Pop attempted on an empty stack.");
}
}
public T top(){
//throws excption if the stack is full
//otherwise returns element on top of stack
T topOfStack = null;
if (!isEmpty())
{
topOfStack = stack[topIndex];
}
else
{
throw new StackUnderflowException("Top attempted on an empty stack.");
}
return topOfStack;
}
}
答案 0 :(得分:0)
由于ArrayStack是您实现的类,并且它不支持该功能,因此您的答案是否定的。
但是你可以向ArrayStack添加一个push方法,接受这样的列表:
public void push(List<T> elements) {
for(T element : elements) {
push(element);
}
}