java循环嵌套原则,Java嵌套循环

Program Description:

Write a program to print 21 rows of X's in the shape of a large X as illustrated below. Be sure so the two rows intersect at the "11" row.

Here is what I want as an output:

rFxHPm.png

Here is what I have so far.

public class Program168h {

public static void main (String [] args) {

String d= "X";

for (int a = 1; a < 23; a++) {

for (int b = a; b >= 1; b--) {

System.out.print(" ");

}

System.out.print(d);

for (int x = a; x < 22; x++) {

System.out.print(" ");

}

System.out.print(d);

System.out.println();

}

}

}

This only produces the first half of the X, I do not know how to produce the lower half.

解决方案

Try this one:

int xSize = 21;

int ySize = 21;

String sign = "X";

for (int i = 0; i < xSize; ++i) {

for (int j = 0; j < ySize; ++j) {

if (i == j) {

System.out.print(sign);

} else if (i == ySize - j - 1) {

System.out.print(sign);

} else {

System.out.print(" ");

}

}

System.out.println();

}

explanation:

The first operate on Xaxis coordinates, second for operates on Yaxis. Our task is to cover diagonal. Covering first diagonal is where coordinateX == coordinateY. In code is if(i==j). These are points (1,1), (2,2)...... Second diagonal are points where (x,y)= (20,1),(19,2),(18,3) .... This situation covers second if(i == ySize - j - 1) .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值