Java嵌套循环 [英] Java nested loops

查看:139
本文介绍了Java嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序说明:

编写一个程序,以大X的形式打印21行X,如下所示.确保两行在"11"行相交.

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 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();
        }
    }
}

这仅产生X的前半部分,我不知道如何产生X的下半部分.

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

推荐答案

尝试以下方法:

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();
}

说明: 第一个用于Xaxis坐标,第二个用于Yaxis坐标.我们的任务是遮盖对角线.覆盖第一个对角线的位置是X坐标== Y坐标.在代码中是if(i == j).这些是点(1,1),(2,2)......第二个对角线是(x,y)=(20,1),(19,2),(18,3)的点. ..这种情况涉及第二if(i == ySize-j-1).

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) .

这篇关于Java嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆