繁体   English   中英

将循环重写为单行循环

[英]Rewrite loops as a one-line loop

是否可以将以下循环重写为单行循环?

for (int i = 0; i < points.length; i++) {
    for (int j = i + 1; j < points.length; j++) {
        if (points[i].equals(points[j])) {
            return "Two vertices coincide therefore a polygon can't be formed";
        }

    }
}
for (int i = 0; i < points.length; i++) {
    for (int j = i + 1; j < points.length; j++) {
        if (points[i].isOnLineSegment(points[j], points[j + 1])) {
            return "There's a vertex on an edge therefore a polygon can't be formed";
        }
    }
}

我想写后置条件,但除了可能将每个循环重写为一行之外,我不知道如何做到这一点。

你在寻找:

for (int i = 0; i < points.length; i++) {
    for (int j = i + 1; j < points.length; j++) {
        if (points[i].equals(points[j])) {
            return "Two vertices coincide therefore a polygon can't be formed";
        }
        if (points[i].isOnLineSegment(points[j], points[j + 1])) {
            return "There's a vertex on an edge therefore a polygon can't be formed";
        }
    }
}

注意:如评论中所述,您在此处的操作points[j + 1] ,如果未找到结果,可能会抛出ArrayIndexOutOfBoundsException ,在这种情况下,我建议使用:

if (j + 1 < points.length && points[i].isOnLineSegment(points[j], points[j + 1])) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM