Java中main方法无法解析pushAtbottom方法问题求助
解决栈底添加元素时pushAtbottom方法无法识别的问题
问题原因及修复步骤:
静态方法无法直接调用非静态方法
main方法是静态方法,而你定义的pushAtbottom是非静态方法——静态方法属于类本身,不能直接访问类的非静态成员(包括方法)。解决方法是把pushAtbottom改成静态方法,或者在main中创建pushatbottom类的实例再调用方法。推荐改成静态方法,因为这个方法不需要依赖类的实例状态。递归逻辑存在两处错误
- 递归调用时错误传入固定值
4,应该使用方法参数data,否则无论你想添加什么元素到栈底,最终都会是4; - 当栈为空时push数据后,没有添加
return语句,会继续执行后续的pop操作,导致空栈调用pop抛出EmptyStackException。
- 递归调用时错误传入固定值
修正后的完整代码:
import java.util.Stack; public class pushatbottom { public static void main(String[] args) { Stack<Integer> s = new Stack<>(); s.push(1); s.push(2); s.push(3); s.push(4); s.push(5); pushAtbottom(6, s); while (!s.isEmpty()) { System.out.println(s.peek()); s.pop(); } } // 改为静态方法,修复递归逻辑 static void pushAtbottom(int data, Stack<Integer> s) { if (s.isEmpty()) { s.push(data); return; // 添加return,终止当前递归分支 } int top = s.pop(); pushAtbottom(data, s); // 传入参数data而非固定值4 s.push(top); } }
内容的提问来源于stack exchange,提问作者Himanshi
相关产品推荐
相关产品推荐

