无法让我的堆栈程序使用流行音乐



所以我正在尝试在我的程序中使用 pop(),但我不完全理解为什么它不会运行。是因为我使用的是扫描仪吗?有人可以解释为什么我的代码告诉我 reverseStack 中的 pop() 不能应用于 (java.util.Stack) pop(stack);^ 这是代码

import java.util.*;
public class reverseStack{
Scanner scan;
Stack <String>stack;
public static void main(String [] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("Type something: ");
Stack<String> stack = new Stack<String>();
scan = new Scanner(scan.nextLine());
while (scan.hasNext()){
stack.push(scan.next());
}
System.out.println(stack);
printStack(stack);  
pop(stack);
}

private static void printStack(Stack<String>s){
if(s.isEmpty())
{
System.out.println("true");
}
else {
System.out.println("false");
}
}
void pop(){
while(!stack.empty()){
System.out.println(stack.pop());
}
}
}

谢谢盖伊

您在reverseStack中定义的pop不需要任何参数。这就是为什么你不能把它作为论据传递stack

我发现了多个问题。不能在main中调用pop非静态方法。

您可能需要更新全局变量中的Stack<String> stack;static Stack<String> stack;并在 main 中初始化它,然后调用pop现在应该声明为static的方法。

或者,您可以将参数传递给stackpop方法并将其声明static

如前所述,您主要问题的答案是您需要在 pop() 方法上设置一个参数。 附加的应该可以工作。

import java.util.Scanner;
import java.util.Stack;
public class ReverseStack2 {
public static void main(String [] args) {
Stack stack = new Stack();
Scanner scan = new Scanner (System.in);
System.out.println("Type something: ");
scan = new Scanner(scan.nextLine());
while (scan.hasNext()){
stack.push(scan.next());
}
System.out.println(stack);
printStack(stack);  
pop(stack);
}
private static void printStack(Stack s){
if(s.isEmpty()) {
System.out.println("true");
} else {
System.out.println("false");
}
}
private static void pop(Stack s){
while(!s.empty()){
System.out.println(s.pop());
}
}
}

最新更新