【发布时间】:2018-10-28 02:25:16
【问题描述】:
在下面的代码中,无限循环发生在 for 循环中。因为如果 mtu = 8。那么 (i = i + (mtu - 8)) 将始终为 0,因为 i 的值永远不会改变。
我插入了一个 if 语句,如果 "(i = i + (mtu - 8))" 等于 0,则执行一些代码,否则打印一条错误消息。我知道这个 if 语句引入了一个新错误 if "mtu = 10"。
打破无限循环的最佳/完整/正确的原因是什么?我应该使用 if 语句吗?还是有其他方法可以解决这个问题?
private static List<String> splitFrame(String message) {
List<String> slicedMessage = new ArrayList<>();
int len = message.length();
if (message.length() > mtu - 8) {
for (int i = 0; i < len; i += (mtu - 8)) { // Infinite loop occurs here. Because if mtu = 8. Then (i = i + (mtu - 8)) will always be 0.
if (!((i += (mtu - 8)) == 0)) { // I try to stop the infinite loop by this if statement. If the sum does not equal 0, then exectute some code.
try {
slicedMessage.add(message.substring(i, Math.min(len, i + (mtu - 8))));
} catch (StringIndexOutOfBoundsException e) {
System.out.println("String Index Out Of Bounds --> Method splitFrame"); // TODO Replace sout with terminal.printDiag from the "MessageSender" class.
}
} else {
System.out.println("MTU can not be set to 8"); // TODO Replace sout with terminal.printDiag from the "MessageSender" class.
}
}
} else {
System.out.println(createFrame(message));
}
return slicedMessage;
}
【问题讨论】:
-
请阅读Halting problem。
-
感谢您的参考。我会调查的。 @ElliottFrisch
标签: java testing exception exception-handling infinite-loop