嵌套循环减量数

问题描述 投票:0回答:2

创建一个要求用户输入数字的类,然后根据int输入打印出以下模式。

所以我制作的代码看起来像这样......

12345 
 1234 
  123 
   12 

但它看起来应该是这样的

    5
   45
  345
 2345
12345
Scanner tri = new Scanner(System.in);
System.out.println("Enter a postive integer.");
int shape = tri.nextInt();
for(int c = shape; c > 1; --c){
    for (int a = 1; a <= shape-c; a++){
        System.out.print(" ");
    }
    for(int d = 1; d <= c; d++){
        System.out.print(d);
    }
    System.out.println(" ");
java nested-loops
2个回答
2
投票

你可以试试下面的代码吗?

Scanner tri = new Scanner(System.in);
System.out.println("Enter a postive integer.");
int shape = tri.nextInt();

for (int c = shape; c >= 1; --c) {
    for (int a = 1; a <= c; a++) {
        System.out.print(" ");
    }
    for (int d = c; d <= shape; d++) {
        System.out.print(d);
    }
    System.out.println(" ");
}

// result
//     5 
//    45 
//   345 
//  2345 
// 12345 

0
投票

您可以使用一些填充,而不是使用嵌套循环。基本上你需要一个只包含空格的字符串,并且与你的数字中的位数一样长。

在循环中,获取数字的子字符串,并用空格填充剩余的字符串。我的代码:

public static void pattern(int number)
    {
        String s=Integer.toString(number);
        String padding="";
        for(int i=0;i<s.length();i++,padding+=" ");
        for(int i=1;i<=s.length();i++)
        {
            System.out.println(padding.substring(i)+s.substring(s.length()-i));
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.