java - Java 中的向后嵌套 For 循环?

标签 java for-loop nested-loops figure

我如何打印这个?

!!!!!!!!!!!!!!!!!!!!!!
\\!!!!!!!!!!!!!!!!!!//
\\\\!!!!!!!!!!!!!!////
\\\\\\!!!!!!!!!!//////
\\\\\\\\!!!!!!////////
\\\\\\\\\\!!//////////

我有:

public class SlashFigure {
    public static void main(String[] args){
        first();
    }
    
    

        public static void first() {
            for ( int i= 1; i<=6; i++) {
                for (int l = 0; l <= 2 * i -2; l++) {
                    System.out.print("\\");
                }
                        for (int e = 22; e >= -2*i + 26; e-=1) {
                            System.out.print("!");
                        }
                                for (int r = 0; r <= 2 * i -2; r++) {
                                    System.out.print("/");
                                }
                      System.out.println();
            }
        }
    }

它正在打印:

\/
\\\!///
\\\\\!!!/////
\\\\\\\!!!!!///////
\\\\\\\\\!!!!!!!/////////
\\\\\\\\\\\!!!!!!!!!///////////

最佳答案

您编写的代码比您需要的多得多。您显示的行的模式很简单 line * 2 *\ + 22 - line * 4 * ! + line * 2 */,刚好超过 6 行,但它始终是 2 个字符的组,因此我们可以将所有字符除以 2,并观察到 ​​\\// 遵循相同的规则规则:

for(int i=0, j=0, k=0; i<6; i++) {
  for(j=0; j<i; j++) { System.out.print("\\\\"); }
  for(k=0; k<(11-2*i); k++) { System.out.print("!!"); }
  for(j=0; j<i; j++) { System.out.print("//"); }
  System.out.println();
}

完成。

关于java - Java 中的向后嵌套 For 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26081434/

相关文章:

java - Java编译器的内部架构

java - 在 HashMap 中向 ArrayList 添加条目

android - 在 TextView 上显示项目数组

powershell - 在 foreach-object 之后处理 SearchResultCollection

java - Java中子类对象如何通过extends关键字访问父类方法或数据成员

java - 获取 float[] 作为 FloatBuffer 类

python - 编写相同的 n 层嵌套循环

c# - 最佳实践 : Nested ForEach

language-agnostic - 构造变量嵌套循环的好方法是什么?

java - 嵌套循环一次仅访问 X 个元素