gpt4 book ai didi

java - 如何创建一个java循环来创建一个带有平方数的三角形?

转载 作者:行者123 更新时间:2023-12-01 17:54:29 25 4
gpt4 key购买 nike

我已经广泛搜索了有关此主题的信息,但没有结果。我真的很挣扎于 Java 循环。

我了解了 For/While 循环的总体思路,但是当真正开始编程时,我遇到了一个又一个错误......

我尝试编写我的程序并理解它的逻辑,但我似乎无法让程序执行我想要它执行的操作。

手头的任务:

Write a program using a Scanner that asks the user for a number n between 1 and 9 (inclusive). The program prints a triangle with n rows. The first row contains only the square of 1, and it is right-justified. The second row contains the square of 2 followed by the square of 1, and is right justified. Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2 and 1, and so forth until n rows are printed.

Assuming the user enters 4, the program prints the following triangle to the console

          1
4 1
9 4 1
16 9 4 1

For full credit, each column should be 3 characters wide and the values should be right justified.

到目前为止,我已经很接近了(暂时不包括用户输入,只是试图至少掌握循环方面,然后我将继续努力):

public class MyClass { 
public static void main(String args[]) {
int rows = 4; // this is the value that the user will enter for # of rows
for (int i = 1; i <= rows; i++) {
for (int j = i; j >= 1; j--) {
System.out.print((j*j)+" ");
}
System.out.println();
}
}
}

打印:

 1
4 1
9 4 1
16 9 4 1

最佳答案

你有两个问题。

首先,您需要在左侧填充数字,以在 3 个字符的空间中生成数字。看System.out.printf("%3d", ...)

其次,您需要打印出额外的空白列。第一行有 3 个空白列,第二行有 2 个空白列,第三行有 1 个空白列,最后一行有 0 个空白列。听起来像是另一个内部循环。

关于java - 如何创建一个java循环来创建一个带有平方数的三角形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46414191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com