我正在尝试使用java Stack来推送String值:将名称输入到它中,从Scanner方法的输入派生。然后我想从堆栈中弹出名称,然后显示堆栈的逻辑和物理元素。我相信我应该使用数组栈但不完全确定,因为我没有太多的指导或Stacks经验。
目前,在编译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代码,通常我会调用Stack中的方法。例如
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;
答案 0 :(得分:1)
您的push(String s)
方法正在调用push()
上的String
这是不正确的,而且push(String s)
的逻辑很复杂,而且很简单,如下面的代码所示评论:
public void push(String s) {
if (isStackFull())
System.out.println ("Stack is Full "); //If Stack full Print Full
else {
stack[top] = s; //just add the string to the top of the stack
top++; //increment top
}
}
答案 1 :(得分:0)
在push方法本身你试图调用stack.push因此它会抛出错误。将stack.push替换为stack [top_index] =字符串。