我在练习 Java 中的链表。所以,我制作了三个节点并给它们赋值 1、2 和 3。当我运行代码时,我想要输出
1 2 3
但是代码给出了输出
333435
我检查了代码,它似乎是正确的。我不知道为什么代码会产生意外的输出。谁能帮帮我。
提前致谢。
class LinkedList{
Node head;
static class Node
{
int data;
Node next;
Node(int d){
data = d;
next = null;
}
}
public void printList(){
Node n = head;
while (n != null){
System.out.print(n.data + ' ');
n = n.next;
}
}
public static void main(String[] args)
{
LinkedList llist = new LinkedList();
llist.head = new Node(1);
Node second= new Node(2);
Node third = new Node(3);
llist.head.next = second;
second.next = third;
llist.printList();
}
}
最佳答案
你的代码是正确的,但你面临的问题在于
System.out.print(n.data + ' ');
改为做
System.out.print(n.data + "");
首先你应该知道:-
单引号用于字符,双引号用于字符串。
当你做的时候
n.data + ' '
它将 ' ' 转换为其 ASCII 值并将其添加到 n.data。 空格的 ASCII 字符是 32。所以,你的输出变成了
1 +32 ==33
2 + 32 = 34
2 + 33 = 35
因此,
333435
并且不会有空格,因为空格被转换成了ASCII值 相似的类型代码将产生相同的输出。
例如:-
System.out.print(n.data + '*');
关于java - 打印在java中产生错误的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37958017/