英文:
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 <= n; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
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 >= 0
. In your case where i <= 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 >= 0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论