gpt4 book ai didi

java - 如何得到如下格式化输出?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:57:14 25 4
gpt4 key购买 nike

我编写了代码以获得以下格式化输出,但是当我输入两位数的行数时,输出格式发生了变化。为什么?我该如何解决这个问题?

      1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1

这是我的代码:

import java.util.*;
class PTri {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of rows for which " +
"triangle has to be constructed");
int numrow = sc.nextInt();
for (int i = 1; i <= numrow; i++) {
for (int j = 1; j <= numrow - i; j++) {
System.out.print(" ");
}
for (int k = 1; k < i * 2; k++) {
System.out.print(Math.min(k, i * 2 - k) + " ");
}
System.out.println();
}
}
}

最佳答案

因为两位数的值会改变整个架构,集合会右移一位。所以你可以这样设置条件。我在数字之间添加了一个额外的空格以提高可见性。

import java.util.*;
class PTri {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of rows for which " +
"triangle has to be constructed");
int numrow = sc.nextInt();
for (int i = 1; i <= numrow; i++) {
for (int j = 1; j <= (numrow - i); j++) {
System.out.print(" ");
}
for (int k = 1; k < i * 2; k++) {
int temp = Math.min(k, i * 2 - k);

if (temp > 9) {
System.out.print(temp + " ");
} else {
System.out.print(temp + " ");
}
}
System.out.println();
}
}
}

关于java - 如何得到如下格式化输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10934848/

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