如何使用java反转打印图案
我写了一个代码,If num = 8
应该显示如下的输出,但代码不显示该结果,有没有人可以帮助我的错?如何使用java反转打印图案
System.out.printf("Enter number of row for pattern to show : ");
int num = input.nextInt();
for(i=num-1;i>0;i--){
for(j=1;j<=i;j++){
if((i+j)%2==0)
System.out.print(0);
else
System.out.print(1);
}
System.out.println();
}
预期输出:
10101010
010101
01010
1010
010
10
0
有防止它编译
- 需要声明i和j在for循环中的几个问题与您的代码。
- 需要字符串转换NUM为整数,通过
Integer.parseInt(num)
- -1是在第一个for循环不必要的(除非你改变了延续条件
i >= 0
,而不是i > 0
)
修复这些...
for (int i = Integer.parseInt(num); i > 0; i--) {
for (int j = 1; j <= i; j++) {
if ((i + j) % 2 == 0) {
System.out.print(0);
} else {
System.out.print(1);
}
}
System.out.println();
}
这给出了稍微不同的输出,即原始问题不输出长度为7的行,它从8到6.另外第6行是'off by one'这几乎可以肯定是原文中的一个错字q题目了。
Original question My output
1) 10101010 10101010
2) <= missing => 0101010
3) 010101 101010 <== mismatch. expected ends in 1
4) 01010 01010
5) 1010 1010
6) 010 010
7) 10 10
8) 0 0
这可以到处工作
for (int i = Integer.parseInt(num); i > 0; i--) {
if (i == 7) {
continue; // conform to broken question
}
if (i == 6) {
System.out.println("010101"); // conform to broken question
continue;
}
...
现在给人的预期输出
10101010
010101
01010
1010
010
10
0
我做了几个修改了代码,并评论说它们是什么。我...
宣布
Scanner
方法称为输入取得
num
int
类型(而不是String
)宣布在
for
循环i
和j
的固定第一个
for
循环(以前是i=num-1
,应该是i=num
)。如下图所示
代码:
Scanner input = new Scanner(System.in); //created Scanner method
System.out.printf("Enter number of row for pattern to show : ");
int num = input.nextInt(); //num should be of type 'int', not String
for(int i=num; i>0; i--) { //Declared 'i', 'i' should equal 'num', not 'num-1'
for(int j=1; j<=i; j++) { //Declared 'j'
if((i+j)%2==0)
System.out.print(0);
else
System.out.print(1);
}
System.out.println();
}
当num
是8,你得到你想要的输出:
Enter number of row for pattern to show : 8
10101010
0101010
101010
01010
1010
010
10
0
我知道这看起来和Adams post非常相似,但是他使用'Integer.parseInt()',而我只是将'num'声明为'int'。我还假设你在你的问题中给出的输出是一个错字(连续两行从0开始)。如果这不是错字,请告诉我,所以我可以编辑我的帖子。 – CodingNinja
@心心伤心如果这个答案对您有帮助,请接受。 – CodingNinja
'反向打印???'怎么串变短每次? –
这个代码是什么? –
对不起,这只是打字错误。程序运行良好,我只是好奇如何获得预期的输出如上所示。 – Crazy