问题描述
- 关于java stack压栈出错
-
public class ReverseString {
Stack word;
Stack sentence;public void reverse(String sentence){ for(int i=0; i<sentence.length(); i++){ char n =sentence.charAt(i); if(n!=' '){ word.push(n); }else{ while(!word.empty()){ this.sentence.push(word.pop()); } this.sentence.push(' '); } } } public void show(){ while(!this.sentence.empty()){ System.out.println(this.sentence.pop()); } } public static void main(String[] args) { new ReverseString().reverse("the sky is blue"); }
}
想不明白为何在执行word.push(n)时 会报 java.lang.NullPointerException
解决方案
Java之Stack --- 栈
Java 用数组实现栈 (Stack),包括栈的初始化,入栈、出栈等操作
Java 数据结构之 Stack(栈)
解决方案二:
word和sentence你都 没有实例化,要用new
时间: 2024-10-21 17:59:09