gpt4 book ai didi

java - 角色不会插入堆栈顶部?

转载 作者:行者123 更新时间:2023-12-01 13:06:24 25 4
gpt4 key购买 nike

因此,对于这个项目,我们有自己的预编程类用于创建堆栈,并且我们需要使用该类来创建和使用堆栈,而不是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com