java - 打印一个正方形三角形。如何镜像数字?

标签 java ascii-art

所以,我已经在这个实验室上为我的编程课工作了一段时间,到目前为止,我认为我走在正确的道路上。

但是,我不太确定如何镜像这些数字。基本上,我的代码只打印三角形的上半部分。不管怎样,这是给我们的实际任务:

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
    9  4  1
       4  1
          1

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

现在这是我到目前为止为我的代码编写的内容:

import java.util.Scanner;
public class lab6 {
    public static void main(String[] args) {
        Scanner kybd = new Scanner(System.in);
        System.out.println(
                "Enter a number that is between 1 and 9 (inclusive): ");

        // this is the value that the user will enter for # of rows
        int rows = kybd.nextInt();

        for (int i = rows; i > 0; i--) {
            for (int j = rows; j > 0; j--)
                System.out.print((rows - j + 1) < i ?
                        "   " : String.format("%3d", j * j));
            System.out.println();
        }
    }
}

这就是当我输入 4 时代码打印的内容:

Enter a number that is between 1 and 9 (inclusive): 
4
          1
       4  1
    9  4  1
16  9  4  1

正如你所看到的,我只能打印出三角形的上半部分。我一直在尝试弄清楚如何镜像它,但我似乎无法弄清楚。我在这个网站上寻求帮助,并在整个互联网上寻求帮助,但我似乎无法做到这一点。

最佳答案

答案是:

public static void main(String... args) {
    Scanner kybd = new Scanner(System.in);
    System.out.println("Enter a number that is between 1 and 9 (inclusive): ");

    int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows

    for (int i = -rows + 1; i < rows; i++) {
        for (int j = -rows; j < 0; j++)
            System.out.print(abs(i) > j + rows ? "   " : String.format("%3d", j * j));
        System.out.println();
    }
}

尝试将其视为如何找到三个线性函数之间的点(笛卡尔)(位于两者之间的三角形面积):

y = 0 // in loops i is y and j is x
y = x + 4
y = -x -4

这是 4 的示例结果:

enter image description here

还有9:

enter image description here

关于java - 打印一个正方形三角形。如何镜像数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60256717/

相关文章:

java - 向 JScrollpane 添加按钮

java - 两类同步

Java - 尝试同时传递无值和 boolean 值,但返回 null

将 ppm 文件转换为 ASCII art

php - 每行打印 n 个星号,递减到 1,然后返回到 n

python - 需要 ASCII 扑克牌才能打印一行

java - jTidy 在整理 HTML 后不返回任何内容

batch-file - 如何在批处理文件中回显包含特殊字符的 ASCII 艺术?

java - 将位图转换为 ASCII 艺术

java - 编辑 PullToRefresh ListView 以从底部刷新