我编写了代码来获取以下格式化输出,但是当我输入两位数的行数时,输出格式会发生变化。为什么?我该如何解决这个问题?
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();
}
}
}
答案 0 :(得分:2)
这是因为双位数值会改变整个架构。集合将转移到一个位置。所以你可以设置这样的条件。(我在数字之间增加了一个额外的空格以提高可见性)
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();
}
}
}
答案 1 :(得分:1)
在这个例子中我计算了数字,并为每个数字添加了一个额外的空格。 值的输出格式为前导零(数字计数)。
public static void main(final String[] args) {
final Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of rows for which triangle has to be constructed");
final int numrow = 100;// sc.nextInt();
final int digits = (int) Math.log10(numrow) + 1;
for (int i = 1; i <= numrow; i++) {
for (int j = 1; j <= numrow - i; j++) {
System.out.print(" ");
for (int l = 0; l < digits; l++) {
System.out.print(" ");
}
}
for (int k = 1; k < i * 2; k++) {
final int value = Math.min(k, i * 2 - k);
System.out.print(String.format("%0" + digits + "d ", value));
}
System.out.println();
}
}
答案 2 :(得分:0)
您可以使用 String.format
方法:
"%2d"
- 格式为两位数字。"%02d"
- 格式为带有前导零的两位数数字。示例:
// int n = 5;
int n = 12;
// number of digits
int digits = String.valueOf(n).length();
// format string
String format = "%" + digits + "d";
// output
System.out.println("n=" + n + ", format=" + format);
IntStream.rangeClosed(1, n)
.mapToObj(i -> IntStream.rangeClosed(-n, i)
.map(Math::abs)
.map(j -> j = i - j)
.filter(j -> j != 0)
.mapToObj(j -> j > 0 ?
String.format(format, j) : " " .repeat(digits))
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
输出:
n=5, format=%1d
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
n=12, format=%2d
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 11 10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 11 12 11 10 9 8 7 6 5 4 3 2 1
另见:Print the sum of the row and column in a 2d array after each row