2017-02-11 72 views
0

我已经开发出一种码打印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

你必须实际调用'diamond2'来让它做任何事情。 – luk2302

+0

我不明白你的问题。你不是在调用第二种方法,那它怎么能做到这一点?你需要从你的主要方法中调用它?! – GhostCat

+0

在'main'方法中输入'diamond2();'在for循环引用的下方引用''在'main'方法中打印diamond'的下半部分,或者更好地将'diamond1'的代码转换为它自己的方法并且在'main'方法中只有两行。 – shash678

回答

0

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

diamond2(); 

加入这行代码到你的主要方法,你会喜欢的方法被调用来完成。