如何用Java打印堆栈?
我尝试了很多不同的方法来打印这个堆栈,但它一直在打印哈希代码,即Problem1$Node@3d4eac69. 我在网上搜索了很多,没有找到任何有用的东西,所以如果有任何建议,我们将非常感谢您的帮助如何用Java打印堆栈?,java,printing,stack,Java,Printing,Stack,我尝试了很多不同的方法来打印这个堆栈,但它一直在打印哈希代码,即Problem1$Node@3d4eac69. 我在网上搜索了很多,没有找到任何有用的东西,所以如果有任何建议,我们将非常感谢您的帮助 import java.util.*; public class Problem1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Reading the
import java.util.*;
public class Problem1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Reading the first integer containing the number of test queries
int N = input.nextInt();
// Initializing the maximum value
int max = Integer.MIN_VALUE;
// Initializing the stack.
Stack<Node> stack = new Stack<Node>();
// Read the query and perform the actions specified.
for(int i = 0; i < N; i++){
int x = input.nextInt();
if(x == 1){
int value = input.nextInt();
Node n = new Node(value);
stack.push(n);
System.out.println(stack);
}
else if(x == 2){
stack.pop();
}
else if(x == 3){
System.out.println(stack.peek());
}
}
}
static class Node{
int data;
public Node(int data){
this.data = data;
}
}
}
import java.util.*;
公共类问题1{
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
//读取包含测试查询数的第一个整数
int N=input.nextInt();
//初始化最大值
int max=整数的最小值;
//初始化堆栈。
堆栈=新堆栈();
//读取查询并执行指定的操作。
对于(int i=0;i
您需要覆盖节点
类中的默认toString
方法(继承自Object),如下所示:
static class Node {
int data;
public Node(int data){
this.data = data;
}
@Override
public String toString() {
return "Node: "+data;
}
}
尝试将对象打印为字符串时,将使用toString
方法。如果没有,它将使用对象
的对象,该对象以这种方式构建字符串
getClass().getName()+'@'+Integer.toHexString(hashCode())
给你一些类似
Problem1的东西$Node@3d4eac69
您需要在节点
类中重写默认的toString
方法(继承自对象),如下所示:
static class Node {
int data;
public Node(int data){
this.data = data;
}
@Override
public String toString() {
return "Node: "+data;
}
}
尝试将对象打印为字符串时,将使用toString
方法。如果没有,它将使用对象
的对象,该对象以这种方式构建字符串
getClass().getName()+'@'+Integer.toHexString(hashCode())
给你一些类似
Problem1的东西$Node@3d4eac69
我在网上搜索了很多,但什么也没找到
-真的吗?我在网上搜索了很多,但什么也没找到
-真的吗?