如何在一行中在for循环中添加变量?

时间:2018-03-14 14:35:46

标签: java loops variables

这是一段Java代码片段,在过去的几天里让我感到非常困惑。目标是在给定位置只插入一行代码,以便在“Given:”之后打印的数字是5050.我不想写多行或更改任何现有的代码行。

public static void main(String args[]) {
    for(int x = 1; x <= 100; x++) {
        // In one line, write code such that 5050 is printed out.
    }
    System.out.println("Given: " + x);
    System.out.println("Expected: 5050");
}

我知道5050是前100个自然数的总和,这在for循环中很明显,它在每次出现时将x设置为每个连续数。如果我能找到一种方法将x的值相互添加,那可能就是一个解决方案。问题是当我退出循环时,我希望x的值为5050,因此“Given:”行打印出5050作为x的值。

我也知道我可以使用另一个变量来存储和的临时值,即y += x;,但是,这是不可能的,因为我无法在循环中多次声明y,并且x的值需要是5050,而不是y。另外,如果我尝试x += x,结果肯定不会是5050,因为for循环执行和加法操作都改变了变量的方式。

那么,实际上是否有解决这个问题的方法呢?

3 个答案:

答案 0 :(得分:5)

您必须进行两项更改。首先,必须x循环之外显示for。否则,在循环之后有一种没有方式来访问它。然后,您所要做的就是将x设置为所需的值(减1),这将在值递增和测试后终止循环。像,

int x;
for (x = 1; x <= 100; x++) {
    x = 5050 - 1;
}
System.out.println("Given: " + x);
System.out.println("Expected: 5050");

输出

Given: 5050
Expected: 5050

其他 合法写入方式就像

for (int x = 1; x <= 100; x++) {
} int x = 5050; {
}
System.out.println("Given: " + x);
System.out.println("Expected: 5050");

在我看来,这不是“真正的”犹太人。请注意,我们终止循环,在该行中添加一个新的x变量和一个空块。

答案 1 :(得分:3)

您可以在此行中关闭for - 循环的括号,并在同一行中引入新变量x

public static void main(String args[]) {
    for(int x = 1; x <= 100; x++) {
        }; String x = "5050"; {
    }
    System.out.println("Given: " + x);
    System.out.println("Expected: 5050");
}

鲍比表的问候......

编辑

正如@ElliottFrish指出的那样,在第一次循环迭代后使用System.exit(0)的以下技巧不起作用,因为范围内仍然没有x

// Doesn't work.
public static void main(String args[]) {
    for(int x = 1; x <= 100; x++) {
       System.out.println("Given: 5050"); System.out.println("Expected: 5050"); System.exit(0);
    }
    System.out.println("Given: " + x);
    System.out.println("Expected: 5050");
}

但是,我们可以通过将给定的System.exit(0);移动到不相关的方法来强制执行此System.out.prinln - 解决方案:

class BobbyForloops {
    public static void main(String args[]) {
        for(int x = 1; x <= 100; x++) {
            System.out.println("Given: 5050\nExpected: 5050"); System.exit(0); }} public static void unrelated(int x) {{
        }
        System.out.println("Given: " + x);
        System.out.println("Expected: 5050");
    }
}

现在它再次编译并输出所要求的内容。但它只是第一种解决方案的变体。

修改:感谢@Dukeling提出使用System.exit(0);的更短的解决方案。 @ Dukeling的解决方案实际上更短,因为它使用break代替System.exit(0)

答案 2 :(得分:1)

代码中的评论并未说明哪里必须放置一行,尽管您的帖子建议需要替换评论。从字面上看,这有效:

public class X {
    private static final String x = "5050";

    public static void main(String args[]) {
        for(int x = 1; x <= 100; x++) {
            // In one line, write code such that 5050 is printed out.
        }
        System.out.println("Given: " + x);
        System.out.println("Expected: 5050");
    }

}