使用三重嵌套的for循环来增加打印的行的长度和数量。

huangapple go评论58阅读模式
英文:

Using a triple nested for loop to increase the length and count of the rows printed

问题

我很好奇如何编写类似这样的代码:
##
##
####
####
####
####
######
######
######
######
######
######
########
########
########
########
########
########
########
########

这是我尝试过的代码:

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i <= 8; i += 2) {
            for (int j = 0; j < i; j++) {
                System.out.print('#');
            }
            System.out.println();
        }
    }
}

这段代码显示:

##
####
######
########

但它没有像字符数量那样多次打印出行数。

因此基本上,它每次增加2,然后显示与循环内字符数量相同的行数。我搞不明白这个。

第三个嵌套的for循环应该是什么样的?


<details>
<summary>英文:</summary>

I am curious as to how to code something like this:
```lang-none
##
##
####
####
####
####
######
######
######
######
######
######
########
########
########
########
########
########
########
########

Here is what I have tried:

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i &lt;= 8; i += 2) {
            for (int j = 0; j &lt; i; j++) {
                System.out.print(&#39;#&#39;);
            }
            System.out.println();
        }
    }
}

This code displays:

##
####
######
########

But it doesn't print the lines as many times as how many characters are there.

So basically, it increments by 2, and then it displays the same amount of lines as the amount of characters inside of the loop. I cant figure this out.

What would the third nested for loop look like?

答案1

得分: 7

这可以通过使用一个循环来实现,使用String::repeat / Collections.nCopies来创建包含N个#字符的行,然后创建N行:

1. String::repeat
自JDK 11于2018年9月发布以来可用的实例方法String::repeat

for (int i = 2; i <= 8; i += 2) {
    String row = "#".repeat(i) + "\n";
    String rows = row.repeat(i);
    System.out.print(rows);
}

2. String::join + Collections.nCopies

import static java.lang.String.join;
import static java.util.Collections.nCopies;

//...

for (int i = 2; i <= 8; i += 2) {
    String row = join("", nCopies(i, "#"));
    String rows = join("\n", nCopies(i, row));
    System.out.println(rows);
}
英文:

This can be done with one loop using String::repeat / Collections.nCopies to create a row containing N # characters and then create N rows:

1. String::repeat<br/>
Instance method String::repeat available since JDK 11 released in September 2018

for (int i = 2; i &lt;= 8; i += 2) {
    String row = &quot;#&quot;.repeat(i) + &quot;\n&quot;;
    String rows = row.repeat(i);
    System.out.print(rows);
}

2. String::join + Collections.nCopies

import static java.lang.String.join;
import static java.util.Collections.nCopies;

//...

for (int i = 2; i &lt;= 8; i += 2) {
    String row = join(&quot;&quot;, nCopies(i, &quot;#&quot;));
    String rows = join(&quot;\n&quot;, nCopies(i, row));
    System.out.println(rows);
}

答案2

得分: 5

我会在你的两个循环之间使用另一个循环。

for (int i = 0; i <= 8; i += 2) {
    for (int k = 0; k < i; ++k) {
        for (int j = 0; j < i; j++) {
            System.out.print('#');
        }
        System.out.println();
    }
}

它会打印出:

##
##
####
####
####
####
######
######
######
######
######
######
########
########
########
########
########
########
########
########
英文:

I'd use an other loop between both of your loops.

for (int i = 0; i &lt;= 8; i += 2) {
    for (int k = 0; k &lt; i; ++k) {
        for (int j = 0; j &lt; i; j++) {
            System.out.print(&#39;#&#39;);
        }
        System.out.println();
    }
}

It prints:

##
##
####
####
####
####
######
######
######
######
######
######
########
########
########
########
########
########
########
########

答案3

得分: 4

你可以在第一个循环内使用两个非嵌套的循环。请参考这个示例:

public static void main(String[] args) {

    for (int i = 0; i <= 8; i += 2) {
        // 使用 StringBuilder 构建要打印的行
        StringBuilder lineBuilder = new StringBuilder();
        // 然后使用一个循环来构建带有所需数量 # 的行
        for (int j = 0; j < i; j++) {
            lineBuilder.append('#');
        }
        // 接着再使用一个相同的循环,但这次打印行
        for (int j = 0; j < i; j++) {
            System.out.println(lineBuilder.toString());
        }
    }
}

所得结果是期望的结果(出于简洁性已省略)。

英文:

You can use two non-nested loops inside the first one. See this example:

public static void main(String[] args) {
	
	for (int i = 0; i &lt;= 8; i += 2) {
		// use a StringBuilder to build up the line to be printed
		StringBuilder lineBuilder = new StringBuilder();
		// then use one loop to build the line with the desired amount of #
		for (int j = 0; j &lt; i; j++) {
			lineBuilder.append(&#39;#&#39;);
		}
		// and then use an identical loop, but this time print the line
		for (int j = 0; j &lt; i; j++) {
			System.out.println(lineBuilder.toString());
		}
	}
}

The result is the desired one (omitted for brevity here).

答案4

得分: 0

我们添加另一个循环:

public static void main(String[] args) {
    for (int i = 0; i <= 8; i += 2)
        for (int j = 0; j < i; j++) {
            for (int k = 0; k < i; k++) {
                System.out.print('#');
            }
            System.out.println();
        }
}
英文:

We add another loop:

public static void main(String[] args) {
    for (int i = 0; i &lt;= 8; i += 2)
        for (int j = 0; j &lt; i; j++) {
            for (int k = 0; k &lt; i; k++) {
                System.out.print(&#39;#&#39;);
            }
            System.out.println();
        }
}

答案5

得分: 0

使用单个for循环的一分号解决方案使用[`String#replace`][1]方法 *自版本1.5*
```java
for (int i = 1; i < 5; i++)
    // 打印包含换行符'\n'的一行
    System.out.print(Collections
            // 'i * 2' 个副本的行"##\n"
            // 返回List<String>
            .nCopies(i * 2, Collections
                    // 'i * 2' 个副本的字符串"#"
                    // 返回List<String>
                    .nCopies(i * 2, "#")
                    // List<String>转字符串
                    // [#, #]
                    .toString()
                    // #, #]
                    .replace("[", "")
                    // #, #
                    .replace("]", "")
                    // ##\n
                    .replace(", ", "") + "\n")
            // List<String>转字符串
            // [##\n, ##\n]
            .toString()
            // ##\n, ##\n]
            .replace("[", "")
            // ##\n, ##\n
            .replace("]", "")
            // ##\n##\n
            .replace(", ", ""));

使用双重嵌套for循环的解决方案,使用String#join方法 自版本:1.8

for (int i = 1; i < 5; i++) {
    for (int j = 0; j < i * 2; j++) {
        String[] arr = new String[i * 2];
        Arrays.fill(arr, "#");
        System.out.print(String.join("", arr));
        System.out.println();
    }
}

使用*双重嵌套IntStream*的解决方案,使用String#repeat方法 自Java 11

IntStream.range(1, 5)
        .forEach(i -> IntStream.range(0, i * 2)
                .forEach(j -> System.out.println("#".repeat(i * 2))));

输出结果:

##
##
####
####
####
####
######
######
######
######
######
######
########
########
########
########
########
########
########
########

<details>
<summary>英文:</summary>

One-semicolon solution with a single for loop using [`String#replace`][1] method *since: 1.5*:
```java
for (int i = 1; i &lt; 5; i++)
    // print one line containing
    // newline symbols &#39;\n&#39;
    System.out.print(Collections
            // &#39;i * 2&#39; copies of rows &quot;##\n&quot;
            // returns List&lt;String&gt;
            .nCopies(i * 2, Collections
                    // &#39;i * 2&#39; copies of string &quot;#&quot;
                    // returns List&lt;String&gt;
                    .nCopies(i * 2, &quot;#&quot;)
                    // List&lt;String&gt; to string
                    // [#, #]
                    .toString()
                    // #, #]
                    .replace(&quot;[&quot;, &quot;&quot;)
                    // #, #
                    .replace(&quot;]&quot;, &quot;&quot;)
                    // ##\n
                    .replace(&quot;, &quot;, &quot;&quot;) + &quot;\n&quot;)
            // List&lt;String&gt; to string
            // [##\n, ##\n]
            .toString()
            // ##\n, ##\n]
            .replace(&quot;[&quot;, &quot;&quot;)
            // ##\n, ##\n
            .replace(&quot;]&quot;, &quot;&quot;)
            // ##\n##\n
            .replace(&quot;, &quot;, &quot;&quot;));

Solution with a double nested for loop using String#join method since: 1.8:

for (int i = 1; i &lt; 5; i++) {
    for (int j = 0; j &lt; i * 2; j++) {
        String[] arr = new String[i * 2];
        Arrays.fill(arr, &quot;#&quot;);
        System.out.print(String.join(&quot;&quot;, arr));
        System.out.println();
    }
}

Solution with a double nested IntStream using String#repeat method since: Java 11:

IntStream.range(1, 5)
        .forEach(i -&gt; IntStream.range(0, i * 2)
                .forEach(j -&gt; System.out.println(&quot;#&quot;.repeat(i * 2))));

Output:

##
##
####
####
####
####
######
######
######
######
######
######
########
########
########
########
########
########
########
########

huangapple
  • 本文由 发表于 2020年10月8日 14:39:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64257047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定