In the code below, the infinite loop occurs at the for loop. Because if mtu = 8. Then (i = i + (mtu - 8)) will always be 0 because the value of i never changes.
I inserted an if statement that says, if "(i = i + (mtu - 8))" does equal 0, then execute some code, else print an error message. I am aware that this if statement has introduced a new bug if "mtu = 10".
What is the best/complete/correct why of breaking infinite loops? Should I be using an if statement? Or is there another way to handle this?
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;
}
Aucun commentaire:
Enregistrer un commentaire