有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在一行中在forloop中添加变量?

下面是一段Java代码,这段代码在过去几天里让我非常困惑。目标是在给定位置只插入一行代码,以便在“给定:”之后打印的数字为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,因此“给定:”行打印出5050作为x的值

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

那么,这个问题真的有解决办法吗


共 (3) 个答案

  1. # 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");
        }
    
    }
    
  2. # 2 楼答案

    你必须做两个改变。首先,必须使xfor循环外可见。否则,在循环之后就没有访问它的方法了。然后,您所要做的就是将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变量和一个空块

  3. # 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.out.prinln移动到一个不相关的方法来强制编译这个System.exit(0);解决方案:

    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)