使用嵌套for循环生成多行String输出

时间:2015-11-21 14:16:42

标签: java

我正在为自己学习Java并遇到以下问题:

  

任务:编写(显式)嵌套for循环以生成以下输出:

    5
  5 5
5 5 5
  5 5
    5

我的想法:

public class Exercises {
    public static void main (String [] args) {
        for (int line = 1; line <= 3; line++) {
            for (int i = 1; i<= -2*line+6; i++){
            System.out.print(" ");
            }   
            System.out.println("5");
        }
        for ( int line = 4; line <= 5; line ++){
            for (int i = 1; i <= 2*line-6; i++){
                System.out.print(" ");
            }
            System.out.println("5");
        }
    }
}

我的输出:

    5
  5
5
  5
    5

我不知道如何在那里获得嵌套循环。你能给我答案,但有些提示吗?

2 个答案:

答案 0 :(得分:0)

试试这个解决方案:

/**
 *
 * @author Adil
 */
public class Exercises {
    public static void main (String [] args) {
        for (int i = 1; i <= 3; i++) {
            for(int s = 4; s > i; s--) {
                // add spacing
                System.out.print(" ");
            }
            for (int j = 1; j < i; j++) {
                //display/add star
                System.out.print("5");
            }
            // add new line
            System.out.println("");
        }
        for (int i = 1; i <= 3; i++) {
            for (int s = 1; s < i; s++) {
                // add spacing
                System.out.print(" ");
            }
            for (int j = 4; j > i; j--) {
                //display/add star
                System.out.print("5");
            }
            // add new line
            System.out.println("");
        }

    }
}

它将产生以下输出:

  5
 55
555
 55
  5

答案 1 :(得分:0)

尝试以下解决方案:

public class Exercises {

    public static void main(String[] args) {

        int noOfColumns = Integer.parseInt(args[0]); // Enter no of 5's in last
                                                        // column
        int noOfRows = noOfColumns;
        int index = noOfColumns;
        int mid = noOfRows / 2;

        for (int i = 0; i < noOfRows; i++) {
            if (i <= mid) {
                index = index - 2;
            } else {
                index = index + 2;
            }

            for (int j = 0; j < noOfColumns; j++) {
                if (j % 2 == 0 && j >= index) {
                    System.out.print("5");
                } else {
                    System.out.print(" ");
                }

            } // End of inner loop

            System.out.println("");
        } // End of outer loop

    }

}