我正在努力构建一种可以打印急需模式的算法。 代码如下:
public static void printPatternH(int size)
{
for (int row = 1; row <= size; row++)
{
for (int col = 1; col <= 2*size; col++)
{
if (col > size + row - 1) {
continue;
}
if (col <= size) {
System.out.print((row + col >= size + 1 ? (row + col)%size : " ") + " ");
}
else {
System.out.print((row + col >= size + 1 ? (row + size)%col : " ") + " ");
}
}
System.out.println();
}
}
我理解,如果size
为9,则中间的最后一个数字将为0 (row + size)%col = 0
,但是我无法找到修改它的方法,而不会更改其余部分值。
答案 0 :(得分:3)
更改
(row + col)%size
到
(row + col - 1) % size + 1
答案 1 :(得分:1)
你可以检查&#34; 0&#34;并在打印之前更换它。
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
它将提供此输出
{{1}}
答案 2 :(得分:0)
尝试
public class Testb
{
int item = 9;
int limit = 5;
int half = item/2;
public static void main(String[] args)
{
//System.out.println("Hello World!");
for(int i=0;i<limit;i++){
for(int j=0;j<half;j++){
if(j<(half-i)){
print(" ");
}else{
print(j-(half-i))
}
}
print(i);
for(int k=half;k<(half+i);k++){
print((half+i)-(k+1));
}
println();
}
}
}
输出:
0
0 1 0
0 1 2 1 0
0 1 2 3 2 1 0
0 1 2 3 4 3 2 1 0
希望对您有帮助
答案 3 :(得分:-1)
以下是您的问题的答案 我希望这对你有所帮助
int rowCount = 1;
System.out.println("Here Is Your Pyramid");
//Implementing the logic
for (int i = noOfRows; i > 0; i--)
{
//Printing i*2 spaces at the beginning of each row
for (int j = 1; j <= i*2; j++)
{
System.out.print(" ");
}
//Printing j value where j value will be from 1 to rowCount
for (int j = 1; j <= rowCount; j++)
{
System.out.print(j+" ");
}
//Printing j value where j value will be from rowCount-1 to 1
for (int j = rowCount-1; j >= 1; j--)
{
System.out.print(j+" ");
}
System.out.println();
//Incrementing the rowCount
rowCount++;
}