Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

java - How to get the following formatted output?

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

Here is my code:

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();
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...