java - 如何让我的代码失去开头的空格?

标签 java loops whitespace

主要问题:输出中存在额外空格

我希望我的代码从我记下的输入中打印出数字的步骤。我的主要问题是空白。我需要输出在一开始就少一个空格。

从我的 System.out.print() 中删除“”; 改变循环 反转循环 分割

import java.util.Scanner;

public class PatternTwo {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter a number 1...9 : ");

        int num = scan.nextInt(); 

        for(int i = 1; i <= num; ++i) { 

        for(int j=2*(num-i); j>=0; j--)

        {

        if (num <= 1)
            System.out.print("");
        else if (num > 1)
            System.out.print(" ");


        }


        for(int j = i; j >= 1; --j) {

        System.out.print(" " + j); 

        }

        System.out.println();

        }

    }

}

}```

I would like the result to be 

Please enter a number 1...9 :  2
  1
 2

Instead of:
Please enter a number 1...9 :  2
   1
  2

最佳答案

这里有两个问题:

  1. j >= 0 应更改为 j > 0

  2. j == i时应避免打印空格

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a number 1...9 :");

    int num = scan.nextInt(); 
    scan.close();

    for (int i = 1; i <= num; i++) { 
        for (int j = 2*(num-i); j > 0; j--)
            if (num > 1)
                System.out.print(" ");
        for (int j = i; j >= 1; j--) {
            if (j != i)
                System.out.print(" ");
            System.out.print(j); 
        }
        System.out.println();
    }
}

我收到以下输出:num = 5:

Please enter a number 1...9 :
5
        1
      2 1
    3 2 1
  4 3 2 1
5 4 3 2 1

关于java - 如何让我的代码失去开头的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58385164/

相关文章:

linux - shell 中的制表符给出不同的宽度

Javascript正则表达式匹配除双空格之外的所有内容,然后替换

java - 如何缩小java堆空间?

Python 从 Stdin Unbuffered 读取和输出

perl - 使用 Perl,如何用换行符替换文件中的所有空格?

javascript - JS 数组循环次数为 1 Off

python - 按名称迭代目录中的图像

java - 多线程访问内存

java - 在同一个类中执行同步和非同步方法

java - Apache Spark 行从时间戳到日期转换异常