我想使用循环在Java中创建一个nxn的图案。

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

I want to create a pattern of nxn in java with the help of loops

问题

我想创建一个类似这样的图案,为什么这段代码有问题?

x x x x

x x x

x x

x

对于任何值 n(这是一个 n x n 的图案)

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = n; i >= 1; i--) {
    for (int j = 1; j <= i; j++) {
        System.out.print("* ");
    }
    System.out.println();
}
英文:

I want to create a pattern like this, why is this code wrong?

x x x x

x x x
  
x x

x

for any value of n( its a nxn pattern )

Scanner sc = new Scanner(System.in);
	int n = sc.nextInt();
	for (int i = n; i &lt;= n; i--) {
		for (int j = 1; j &lt;= i; j++) {
			System.out.print(&quot;* &quot;);
		}
		System.out.println();
	}

}

答案1

得分: 1

你的条件错误,应为 i >= 0。在你的情况下,当 i <= n 时,“i”会递减并永远不会达到“停止条件”。

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = n; i >= 0; i--) {
    for (int j = 1; j <= i; j++) {
        System.out.print("* ");
    }
    System.out.println();
}
英文:

You condition is wrong it should be i &gt;= 0. In your case where i &lt;= n, "i" is decremented and will never reach "stop condition".

Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		for (int i = n; i &gt;= 0; i--) {
			for (int j = 1; j &lt;= i; j++) {
				System.out.print(&quot;* &quot;);
			}
			System.out.println();
		}

huangapple
  • 本文由 发表于 2020年10月13日 12:40:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/64328634.html
匿名

发表评论

匿名网友

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

确定