主要问题:输出中多余的空格
我希望我的代码从我输入的内容中打印出一些数字。我的主要问题是空白。在开始时,我需要将输出空间减少一个空白。
从我的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
这里有两个问题:
j >= 0
应该更改为 j > 0
您应避免在以下情况下打印空白 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句