gpt4 book ai didi

java - 具有多个输入的 for 循环不会停止

转载 作者:行者123 更新时间:2023-11-30 07:13:27 25 4
gpt4 key购买 nike

我在使用似乎没有停止的 for 循环时遇到了一些问题。当我第一次调用 PutGenerator 时,自定义列表中只有一个项目,它工作得很好。当我再次运行 9 个项目时,它会继续运行。你能指出我正确的方向吗?

编辑:我可以让测试第二次运行,但之后就什么也没有了。

input: 
1
5
3
3 2 4
1 5 2
3 6 4
1
6
2
5 6
6 7

代码:

 public static void outputGenerator (CustomList [] list, PrintWriter  printWriter) {
int size2;
int valueToPrint;
CustomList listToBuild;
int length;
length = list.length;
System.out.println("len: " + length);

//print out the results to a .txt file
try {

printWriter.println("Matrix read: ");
printWriter.println();
printWriter.println("------------------" +
"---------------------");
printWriter.println();
printWriter.flush();

for (int x = 0; x < length; x++){
System.out.println("test");
listToBuild = list[x];
size2 = listToBuild.sizeOfList();
System.out.println("size2 " + size2);

for (int y = 0; y < size2; y++) {
System.out.println("y: " + y);
valueToPrint = listToBuild.ValueOfNode(y);
printWriter.println(valueToPrint);
System.out.println("val" + valueToPrint);
printWriter.flush();

}
printWriter.println();
}
return;
}catch (Exception e) {
e.printStackTrace();
}
}

自定义链接列表代码:

public class CustomList {

private Node firstNode;
private Node end;
private Node header;
private int sizeOfMatrix;
private int sizeOfList;




//constructor to set all to blank
public CustomList() {
firstNode = null;
end = null;
header = null;
sizeOfMatrix = 0;
sizeOfList = 0;

}

public void addToList(int dataToSave) {

Node node = new Node (dataToSave);

if (firstNode == null) {
firstNode = node;
firstNode.next = end;
firstNode.before = header;
}

else if (end == null) {
end = node;
end.before = firstNode;
firstNode.next = end;

}

else
end.next = node;
node.before = end;
end = node;

sizeOfMatrix++;
}

public void setHeader (int dataToUse){

Node headerNode = new Node(dataToUse);
header = headerNode;
header.next = firstNode;
}

public void print() {
Node zNode = firstNode;
System.out.println("Test");
if(firstNode == null){
System.out.print("EMPTY");
return;
}

while (zNode != null) {
System.out.println(zNode);
zNode = zNode.next;
}
}




public int sizeOfList() {

Node zNode = firstNode;
sizeOfList = 0;

while( zNode != null) {

zNode = firstNode.next;
sizeOfList++;
}
return sizeOfList;
}



public int ValueOfNode( int column ) {
int counter = 0;
Node zNode = firstNode;

while (zNode != null) {

if (column == counter){
return zNode.numInMatrix();
}

else
zNode = firstNode.next;
counter++;
}

return -1;
}

最佳答案

当你做的时候

size2 = listToBuild.sizeOfList();

sizeOfList() 每次调用都会返回相同的值。

我猜,你没有改变firstNode的值。另外,我对你的函数做了一些修改。

public int sizeOfList() {

Node zNode = firstNode;
sizeOfList = 0;

while( zNode != null) {
zNode = zNode.next;
sizeOfList++;
}
return sizeOfList;
}

关于java - 具有多个输入的 for 循环不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38801103/

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