因此,对于这个项目,我们有自己的预编程类用于创建堆栈,并且我们需要使用该类来创建和使用堆栈,而不是 Java 自带的 Stacks 类。我遇到的问题是,当我将字符插入堆栈顶部时,它仍然为空,您知道为什么会发生这种情况吗?
这是我们的 stacks 类中用于推送的代码
StackOfCharacters.java(推送方法):
/**
* Puts the character value at the top of the stack.
* @param value adds specified character to the stack
*/
public void push ( Character value )
{
//if the stack is full, allocate a larger array
if ( full() )
makeLarger();
//add the new value to the top of the stack
if (value != null) {
list[size] = value;
size++;
}
}
但是当我调用它时,它显示为空
平衡.java
public void isBalanced(String x){
char d = x.charAt(1);
System.out.println(d);
new StackOfCharacters();
new StackOfCharacters().push(x.charAt(1));
System.out.println(new StackOfCharacters().peek());
System.out.println(new StackOfCharacters().empty());
}
主类:
Scanner input = new Scanner(System.in);
System.out.print("Type a string to Balance Check: ");
String s = input.nextLine(); // input String
System.out.println();
new BalanceChecks().isBalanced(s);
StackOfCharacters.java 文件的编码据说是 100% 正确的,我只是很困惑为什么除了推送之外一切都正常?
谢谢!
最佳答案
您一直在创建新对象,而不是使用相同的对象。创建类的实例并将字符推送到该实例:-)
StackOfCharacters soc = new StackOfCharacters();
soc.push(1);
System.out.println(soc.peek());
关于java - 角色不会插入堆栈顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23228029/