gpt4 book ai didi

java - 使用 toString 方法代替 Print 方法

转载 作者:太空宇宙 更新时间:2023-11-04 14:23:59 25 4
gpt4 key购买 nike

如何在代码中使用 toString 方法,而不是下面的自定义 print 方法?我当前代码的输出正是它应该的,但我的导师希望我“使用 toString 并获得相同的输出”。我很困惑,不知道该怎么做。

这是我的代码:

public class LinkedListIntro {

//print method
public static void print(Node temp) {
System.out.print("[");
while (temp.getNext() != null) {
System.out.print(temp.getData() + ", ");
temp = temp.getNext();
}
System.out.println(temp.getData() + "]");
}

public static void main(String[] args) {
Node start = null;
Node temp = null;

for (int i = 1; i <= 5; i++) {
if (start == null) {
start = new Node(i);
temp = start;
} else {
temp.setNext(new Node(i));
temp = temp.getNext();
}
}

//3. printing data
print(start);

//4. removing 4
temp = start;
Node n = temp.getNext();

while (n.getNext() != null) {
if ((int) n.getData() == 4) {
temp.setNext(n.getNext());
n = null;
break;
}
temp = temp.getNext();
n = n.getNext();
}

//5. printing data again after removing 4
print(start);

//6. adding 100 between 1 and 2
temp = start;
Node n1 = temp.getNext();

while (n1.getNext() != null) {
if ((int) temp.getData() == 1) {
temp.setNext(new Node(100));
temp = temp.getNext();
temp.setNext(n1);
}
temp = temp.getNext();
n1 = n1.getNext();
}

//7. printing data again after adding 100
print(start);

//8. removing first node
temp = start;
start = start.getNext();
temp = null;

//printing data after removing 1st node
print(start);

//9. add 0 to beginning
temp = start;
start = new Node(0);
start.setNext(temp);

//printing the final data
print(start);
}
}
<小时/>
public class Node<E>
{

private E data;
private Node next;

public Node(E data) {
this.data = data;
this.next = null;
}

public E getData(){
return data;
}

public Node getNext() {
return next;
}

public void setNext(Node next) {
this.next = next;
}

public String toString() {
return data.toString();
}
}

最佳答案

使用当前 print 方法中的代码在 NodetoString() 方法中构建输出字符串。之后,print 可以将 Node temp 参数传递给 System.out.print(),因为它使用 toString() 内部。

public static void print(Node temp) { //irrelevant method by now
System.out.print(temp);
}

public class Node<E>{

private E data;
private Node next;

//...

public String toString() {
String ouput = "";
Node node = this;
while(node.getNext() != null) {
output += node.getData() +", ";
node = node.getNext();
}
return ouput;
}
}

关于java - 使用 toString 方法代替 Print 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26869118/

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