最好/完全/正确的处理无限循环的原因是什么? (JAVA)

时间:2018-10-28 02:25:17

标签: java testing exception exception-handling infinite-loop

在下面的代码中,无限循环发生在for循环处。因为如果mtu = 8,则(i = i +(mtu-8))始终为0,因为i的值永远不变。

我插入了一条if语句,如果“(i = i +(mtu-8))”等于0,则执行一些代码,否则打印一条错误消息。我知道,如果“ mtu = 10”,则此if语句引入了一个新的错误。

为什么打破无限循环的最好/完全/正确的是什么?我应该使用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;
}

1 个答案:

答案 0 :(得分:0)

由于mtu的值没有改变,因此如果mtu = 8,则无需进入循环。

private static List<String> splitFrame(String message) {
    List<String> slicedMessage = new ArrayList<>();
    int len = message.length();
    int diff = mtu - 8;
    if (diff != 0 && len > diff) {
        for (int i = 0; i < len; i += diff) {
            try {
                slicedMessage.add(message.substring(i, Math.min(len, i + (diff))));
            } 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(createFrame(message));
    }
    return slicedMessage;
}