Java nested loops

前端 未结 3 683
故里飘歌
故里飘歌 2021-01-29 14:10

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 \

3条回答
  •  春和景丽
    2021-01-29 14:39

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

提交回复
热议问题