我正在嘗試使用java堆棧將字符串值:名稱導入到它中,派生自Scanner方法的輸入。然後,我想從堆棧中彈出名稱,並顯示堆棧的邏輯和物理元素。我相信我應該使用數組堆棧,但不完全確定,因爲我沒有太多的Stack或Stacks經驗。與字符串元素一起使用Java堆棧
當編譯Stack.java文件時出現以下錯誤。
Stack.java:24: cannot find symbol
symbol : method push(java.lang.String)
location: class java.lang.String[]
stack.push(s);
我一直在研究這個,日子嘗試不同的代碼,但我很新的這一點,我已經跑出去的方法來操作的代碼,使其工作。
我非常感謝一些建議...... tnx!
這裏是我的Stack類代碼:
import java.lang.*;
import java.util.*;
public class Stack { //Create Class
private String stack[] ;
private int top;
private static final int SIZE = 5;
String name;
Scanner scan = new Scanner(System.in);
public Stack(int SIZE){
stack = new String [SIZE];
top = 0;
}
public void push(String s) { //Method to Insert
if (isStackFull())
System.out.println ("Stack is Full "); //If Stack full Print Full
else {
while (scan.hasNextLine()){
s = scan.nextLine();
stack.push(s);
}
stack[top] = s;
top++;
}
}
public String pop() { //Method to Delete
if (isStackEmpty())
System.out.println ("Stack is Empty "); //If Stack empty print Empty
else{
String value = stack[top];
top--;
return value;
}
return stack[top];
}
public String toString(){ //Method print Logical Stack
if (isStackEmpty())
System.out.println ("Stack is Empty "); //If Stack empty print Empty
else
System.out.println("\nThe Stack");
String result = "";
for (int j=0; j < top; j++)
result = result + stack[j].toString() + "\n";
return result;
}
public boolean isStackEmpty() { //Method boolean type to check empty Stack
return (top == 0);
}
public boolean isStackFull() { //Method boolean type to check full Stack
return (top == (SIZE-1));
}
}
對於StackTest代碼,一般我調用棧的方法。例如。
public class StackTest { //Create class
public static void main(String[] args){ //Main Method
Stack n = new Stack(); //Declare variables
Scanner in = new Scanner(System.in);
String response;
char x;
和
while(x != 'q' && x != 'Q'){ //While loop initiates if no q or Q char input
switch(x){ //Start of swtich for insert, delete, print physical, logical or default quite
case 'i':
n.push();
System.out.println ("Inserted item from Stack");
break;
case 'd':
n.pop();
System.out.println ("Deleted item from Stack");
break;
case 'p':
n.toString();
System.out.println ("Printed Physical Stack ");
break;
'stack'是一個String數組,它沒有'push'方法。 – shmosel
如果您需要一個不需要線程安全性的'Stack'實現,['ArrayDeque'](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayDeque.html)是可取的。 – 4castle