java—我似乎无法使用for循环获得正确的显示模式?

ajsxfq5m  于 2021-06-30  发布在  Java
关注(0)|答案(3)|浏览(294)

我试图通过严格使用for循环来显示这个模式,但是我一直以代码下面的内容结束。

1*****

* 2****
**3***
***4**
****5*
*****6
public class PA4 {
    public static void main(String[] args) {
        for (int line = 1; line <= 6; line++) {
            for (int j = 1; j <= (line - 1); j++) {
                System.out.print("*");
        }
        System.out.print(line);
        for (int j = 1; j <= (line + 6); j++) {
            System.out.print("*");
        }
        System.out.println();
    }
}
}
1*******

* 2********
**3*********
***4**********
****5***********
*****6************
0sgqnhkj

0sgqnhkj1#

public static void main(String[] args) {
    int n = 5;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < i; j++) {
            System.out.print("*");
        }
        System.out.print(i + 1);
        for (int j = 0; j < n - i - 1; j++) {
            System.out.print("*");
        }
        System.out.print("\n");
    }
}
fv2wmkja

fv2wmkja2#

for (int j = 1; j <= (line + 6); j++) {
        System.out.print("*");
    }

用以下代码替换第二个for循环-

for (int j = (line + 1); j <= 6; j++) {
        System.out.print("*");
    }

https://logicblocks.blogspot.com

vsnjm48y

vsnjm48y3#

请注意 j <= (line - 1) 与相同 j < line ,在原始代码中。
任何价值 n :

public static void main(String[] args) {
  int n = 6;

  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      if (j == i) System.out.print(j+1);
      else System.out.print("*");
    }

    System.out.println();
  }
}

编辑现在我知道你只能用于循环,让我们这样想:

int n = 6;

  for (int i = 0; i < n; i++) {
    // iterate from 0 to < i, printing an *

    // now we're at i, so we just print our number (which is i+1)

    // now we go back to iterating, from i+1 to <n
    // (continuing where we left off)

    // finally, print a newline since we're done with this row
  }

相关问题