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

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


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


从我的 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


12345678_0001
浏览 141回答 2
2回答

红颜莎娜

这里有两个问题:j >= 0应该改为j > 0您应该避免在以下情况下打印空白区域:j == ipublic static void main(String[] args) {&nbsp; &nbsp; Scanner scan = new Scanner(System.in);&nbsp; &nbsp; System.out.println("Please enter a number 1...9 :");&nbsp; &nbsp; int num = scan.nextInt();&nbsp;&nbsp; &nbsp; scan.close();&nbsp; &nbsp; for (int i = 1; i <= num; i++) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; for (int j = 2*(num-i); j > 0; j--)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (num > 1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(" ");&nbsp; &nbsp; &nbsp; &nbsp; for (int j = i; j >= 1; j--) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (j != i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(" ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(j);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }}我收到以下输出num = 5:Please enter a number 1...9 :5&nbsp; &nbsp; &nbsp; &nbsp; 1&nbsp; &nbsp; &nbsp; 2 1&nbsp; &nbsp; 3 2 1&nbsp; 4 3 2 15 4 3 2 1

暮色呼如

尝试添加一个第一次跳过空格的 if 语句,例如:for(int j = i; j >= 1; --j)&nbsp;{&nbsp; &nbsp; if(j == i)&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(j);&nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(" " + j);&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java