2014-09-24 11 views
0

我正在開發一個程序,幫助學生按順序學習所有總統。我正在使用堆棧。我想和所有的總統組成一個堆棧。然後,用戶將輸入一個總統姓名,程序會將輸入與堆棧頂部進行比較。有沒有辦法在每次不使用推送方法的情況下將多個字符串添加到堆棧中

我想知道是否有方法使用字符串填充我的堆棧而不使用.push方法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

什麼阻止你將是推動多個項目進棧的方法? – Eran 2014-09-24 04:29:54

回答

0

由於ArrayStack是可以實現的類,它穿上」 t支持該功能,你的答案是否定的。

但你可以添加一個推法ArrayStack像這樣的accepte列表:

public void push(List<T> elements) { 
    for(T element : elements) { 
     push(element); 
    } 
} 
相關問題