如何获得以下格式的输出? [英] How to get the following formatted output?

查看:47
本文介绍了如何获得以下格式的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了代码以获取以下格式化的输出,但是当我输入两位数的行数时,输出格式会更改.为什么?我该如何解决?

I wrote the code to get the following formatted output, but when I enter number of rows in double digits, the output format changes. Why? How can I fix this?

      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();
        }
    }
}

推荐答案

这是因为两位数的值将更改整个体系结构.该集合将向右移一位.因此,您可以设置这样的条件.我在数字之间添加了一个额外的空格,以提高可见度.

It's because the value in double digit will change the whole architecture.The set will shift to right one place. So you can put a condition like this. I have added one extra space between numbers to improve visibility.

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();
        }
    }
}

这篇关于如何获得以下格式的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆