加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何在Java中将这个数字表打印到控制台?

发布时间:2020-12-15 08:28:57 所属栏目:Java 来源:网络整理
导读:要求一个自然数n,我想以这种格式打印到控制台: 1 2 1 3 2 1 4 3 2 1 5 4 3 2 1 . . .n . . . 5 4 3 2 1 输入4,这是我到目前为止: 1 21 321 4321 我想在数字之间添加一个空格.这是我的代码: import java.util.Scanner;public class PatternTwo { public st
要求一个自然数n,我想以这种格式打印到控制台:

1
              2 1
            3 2 1
          4 3 2 1
        5 4 3 2 1
          .
          .
          .
n . . . 5 4 3 2 1

输入4,这是我到目前为止:

1
   21
  321
 4321

我想在数字之间添加一个空格.这是我的代码:

import java.util.Scanner;
public class PatternTwo {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int userInput;
        System.out.println("Please enter a number 1...9 : ");
        userInput = in.nextInt();
        String s="";
        int temp = userInput;
        for(int i=1; i<=userInput; i++ ) {

            for (int k= userInput; k>=i; k-- ) {
                System.out.printf(" ");
            }

            for(int j =i; j>=1; j-- ) {
                System.out.print(j);
            }


            System.out.println("");
        }

    }

}

解决方法

在要打印的数字前面添加一个空格,并将上面的空格加倍,使其不是金字塔.像这样的东西:

import java.util.Scanner;
public class PatternTwo {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int userInput;
        System.out.println("Please enter a number 1...9 : ");
        userInput = in.nextInt();
        String s="";
        int temp = userInput;
        for(int i=1; i<=userInput; i++ ) {

            for (int k= userInput; k>i; k-- ) { // <- corrected condition
                System.out.printf("  ");
            }

            for(int j = i; j>=1; j-- ) {
                System.out.print(j);

                // check if not 1 to avoid a trailing space
                if (j != 1) {
                    System.out.print(" ");
                }
            }


            System.out.println("");
        }

    }

}

编辑

感谢/u/shash678我纠正了我的解决方案,删除了所有不必要或错误的空格

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读