未显示第二种方法的输出

时间:2017-02-11 20:29:55

标签: java

我开发了一个打印2颗钻石的代码,代码是:

public class Diamond {
public static final int DIAMOND_SIZE = 5;

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    System.out.println("Diamond Height: " + DIAMOND_SIZE);
    System.out.println("Output for: For Loop");

    int noOfRows = DIAMOND_SIZE;

    //Getting midRow of the diamond
    int midRow = (noOfRows)/2;

    //Initializing row with 1
    int row = 1;

    //Printing upper half of the diamond
    for (int i = midRow; i > 0; i--)
    {
        //Printing i spaces at the beginning of each row
        for (int j = 1; j <= i; j++) {
            System.out.print(" ");
        }

        //Printing j *'s at the end of each row
        for (int j = 1; j <= row; j++) {
            System.out.print("* ");
        }

        System.out.println();

        //Incrementing the row
        row++;
    }

    //Printing lower half of the diamond
    for (int i = 0; i <= midRow; i++) {
        //Printing i spaces at the beginning of each row
        for (int j = 1; j <= i; j++) {
            System.out.print(" ");
        }

        //Printing j *'s at the end of each row
        int mid = (row+1) / 2;
        for (int j = row; j > 0; j--) {
        if(i==0 && j==mid) {
            System.out.print("o ");
        }
        else {
            System.out.print("* ");
        }
        }

        System.out.println();

        //Decrementing the row
        row--;
    }
}

public static void diamond2() {
        // writing the top portion of the diamond
        int y = DIAMOND_SIZE;
        int i = 1;
        while (i < y + 1) {
              int spaces = 0;
              while (spaces < y - i) {
                    spaces++;
                    System.out.print(" ");
              }
              int j = i;
              while (j > 0) {
                    j--;
                    System.out.print("* ");
              }
              System.out.println();
              i++;
        }

        // writing the bottom half of the diamond
        i = y - 1;
        while (i > 0) {
              int spaces = 0;
              while (spaces < y - i) {
                    spaces++;
                    System.out.print(" ");
              }
              int j = i;
              while (j > 0) {
                    System.out.print("* ");
                    j--;
              }
              System.out.println();
              i--;
        }
}
}

我从中得到的结果是:

Diamond Height: 5
Output for: For Loop
  * 
 * * 
* o * 
 * * 
  *

这是第一种方法,第二种方法的输出没有显示。当我注释掉第一种方法时,则显示第二种方法的输出。我做错了什么?

1 个答案:

答案 0 :(得分:0)

为了访问作为第二种方法的代码块,您需要正式调用方法头。在你的情况下,它可以像这样完成

diamond2();

将这行代码添加到您希望调用该方法的main方法中。