执行堆栈操作以在没有集合api的情况下在java中推送字符串

问题描述 投票:0回答:2

在我的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

java stack
2个回答
0
投票

你的push()方法和潜在的arr变量应该是String类型。

String arr[] = new String[capacity];

public void push(String pushedElement) {
  ...
}

0
投票

声明您的数组只存储整数。更不用说,stackDemo.push方法也声明只接受int参数。

int arr[] = new int[capacity];


public void push(int pushedElement) {

你应该尝试推入整数。

  stackDemo.push(1);  
  stackDemo.push(2);  
  stackDemo.push(3); 
© www.soinside.com 2019 - 2024. All rights reserved.