我想做一个这样的模式,这个模式类似于flyords三角形,但是备用行的顺序是相反的,我尝试了一些东西,却无法获得预期的输出
1
3*2
4*5*6
10*9*8*7
11*12*13*14*15
我试过这个东西,
public static void main(String args[])
{
int count=1;
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
if(i>j) {
System.out.print(count + "*");
count++;
}else {
System.out.print(count);count++;
}
}System.out.println();
}
}
}
我得到的结果是,
1
2*3
4*5*6
7*8*9*10
11*12*13*14*15
如何反转备用行:(
答案 0 :(得分:2)
您可以使用三元运算符确定在行号的奇数上添加多少,并在for循环的定义中设置该行的正确起始值:
public static void main(String args[])
{
int currentNumber = 0;
for (int line = 1; line <= 5; currentNumber += (line++))
{
for (int i = 1; i <= line; i++)
{
System.out.print(currentNumber + ((line % 2 == 1) ? i : line + 1 - i));
if (i < line)
System.out.print("*");
}
System.out.println();
}
}
答案 1 :(得分:0)
您可以为每个偶数行启动该行中通常最后的数字。这是您的起始号码i-1
比正常情况下大,而不是count++
您count--
。
public static void main(String args[])
{
int count=1;
for(int i=1;i<=5;i++)
{
if (i%2 == 0)
{
count += i-1; // there are i numbers on this row, highest is (i-1) larger than lowest
for(int j=1;j<=i;j++)
{
if(i>j) {
System.out.print(count + "*");
count--;
}else {
System.out.print(count);
}
}System.out.println();
count += i // count was lowest number on current row. Increase it to lowest number on next row.
}
else
{
for(int j=1;j<=i;j++)
{
if(i>j) {
System.out.print(count + "*");
count++;
}else {
System.out.print(count);count++;
}
}System.out.println();
}
}
}
答案 2 :(得分:0)
int count = 1;
int plus = 0;
for (int i = 1; i <= 10; i++) {
plus = i - 1;
for (int j = 1; j <= i; j++) {
if (i % 2 == 0) {
if (i > j) {
System.out.print(count + plus + "*");
plus-=2;
count++;
} else {
System.out.print(count+plus);
count++;
}
} else {
if (i > j) {
System.out.print(count + "*");
count++;
} else {
System.out.print(count);
count++;
}
}
}
System.out.println();
}