我如何使我的代码在一开始就失去空白?

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

主要问题:输出中有多余的空格

我希望我的代码从我输入的输出中打印出一个数字步。我的主要问题是空白。我需要在开始时将输出空间减少一个空白。

从我的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
java loops whitespace
2个回答
0
投票

尝试添加一个if语句,该语句在第一次时会跳过空白:

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

0
投票

您只需要将j>=0更改为j>0

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

0
投票

您在这里有两个问题:

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
© www.soinside.com 2019 - 2024. All rights reserved.