[英]How to reverse print a pattern using java
I write a code that If num = 8
should show a output as below, but the code do not show that result, could any one help whats my wrong? 我编写了一个代码,
If num = 8
则应显示如下输出,但该代码未显示该结果,请问有人可以帮我解决吗?
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();
}
Expected output : 预期产量:
10101010
010101
01010
1010
010
10
0
There were a few issues with your code preventing it compiling 您的代码存在一些问题,无法编译
Integer.parseInt(num)
Integer.parseInt(num)
将String num转换为整数 i >= 0
instead of i > 0
) i >= 0
而不是i > 0
) Fixing these... 修复这些...
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();
}
This gives a slightly different output, ie the original question does not output a line of length 7, it goes from 8 to 6. Also line 6 is 'off by one' This is almost certainly a typo in the original question. 这样给出的输出会稍有不同,即原始问题不会输出长度为7的行,它从8到6。行6也“偏离了一位”这几乎可以肯定是原始问题中的错字。
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
This can be worked around 这可以解决
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;
}
...
Which now gives the expected output 现在给出预期的输出
10101010
010101
01010
1010
010
10
0
I made a couple changes to your code, and commented what they were. 我对您的代码进行了一些更改,并评论了它们的含义。 I...
一世...
declared Scanner
method called input 声明的
Scanner
方法称为输入
made num
of type int
(rather than String
) num
int
类型的num
(而不是String
)
Declared i
and j
in your for
loops 在
for
循环中声明了i
和j
fixed the first for
loop(used to be i=num-1
, should be i=num
). 修复了第一个
for
循环(以前是i=num-1
,应该是i=num
)。
Code shown below: 代码如下所示:
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();
}
And when num
is 8, you get the output you desired: 当
num
为8时,将获得所需的输出:
Enter number of row for pattern to show : 8
10101010
0101010
101010
01010
1010
010
10
0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.