代码之家  ›  专栏  ›  技术社区  ›  Riya

在java中执行堆栈操作以推送字符串,而不使用集合api

  •  0
  • Riya  · 技术社区  · 7 年前

    在我的java程序中,我想执行像push和pop这样的堆栈操作。我还想在堆栈操作中推字符串,但当我尝试推字符串时。我在截图中提到了错误。我应该如何更改push方法才能成功运行程序。

    代码::

    public class DataStack {
    
    private static final int capacity = 3;  
     String arr[] = new String[capacity];  
     int top = -1;  
    
     public void push(String pushedElement) {  
      if (top < capacity - 1) {  
       top++;  
       arr[top] = pushedElement;    
       printElements();  
      } else {  
       System.out.println("Stack Overflow !");  
      }  
     }  
    
     public void pop() {  
      if (top >= 0) {  
       top--;  
       System.out.println("Pop operation done !");  
      } else {  
       System.out.println("Stack Underflow !");  
      }  
     }  
    
     public void printElements() {  
      if (top >= 0) {  
       System.out.print("Elements in stack : ");  
       for (int i = 0; i <= top; i++) {  
        System.out.println(arr[i]);  
       }  
      }  
     }  
    
     public static void main(String[] args) {  
      DataStack stackDemo = new DataStack();  
    
      stackDemo.push("china");  
      stackDemo.push("india"); 
      stackDemo.push("usa");    
     }
    }
    

    错误::

    enter image description here

    2 回复  |  直到 7 年前
        1
  •  0
  •   Karol Dowbecki    7 年前

    你的 push() 方法和基础 arr 变量应为 String 类型

    String arr[] = new String[capacity];
    
    public void push(String pushedElement) {
      ...
    }
    
        2
  •  0
  •   Jerin Joseph    7 年前

    数组声明为仅存储整数。更不用说 stackDemo.push 方法还声明只接受int参数。

    int arr[] = new int[capacity];
    
    
    public void push(int pushedElement) {
    

    你应该尝试输入整数。

      stackDemo.push(1);  
      stackDemo.push(2);  
      stackDemo.push(3);