2012-10-08 85 views
-2

我應該寫一個嵌套循環,輸出以下:for循環的Java ...創建金字塔

    1 
       1 2 1 
      1 2 4 2 1 
      1 2 4 8 4 2 1 
     1 2 4 8 16 8 4 2 1 
    1 2 4 8 16 32 16 8 4 2 1 
1 2 4 8 16 32 64 32 16 8 4 2 1 

我應該使用兩種方法。

主要方法只應該從用戶獲取所需的行數。 我應該寫稱爲printPyramid另一種方法是:

  1. 擁有的行數
  2. 打印與行數
  3. 沒有返回值金字塔。

到目前爲止,我有:

import java.util.Scanner; 

    public class Pyramid { 


    //Getting number of rows, calling printPyramid in main method 

    public static void main(String[] args) { 

    Scanner input = new Scanner(System.in); 

    //Get user input = number of lines to print in a pyramid 
    System.out.println("Enter the number of lines to produce: "); 
    int numLines = input.nextInt(); 

    //call method: 
    printPyramid(); 

    }//End of main method 

    //Making a new method... 

    public static void printPyramid (int numLines) { 

    int row; 
    int col; 

    row = 0; 
    col = 0; 

     for (row = 1; row <= numLines; row++){ 
      //print out n-row # of spaces 
      for (col = 1; col <= numLines-row; col++){ 
       System.out.print(" "); 
      } 

      //print out digits = 2*row-1 # of digits printed 
      for (int dig= 1; dig <= 2*row-1; dig++){ 
       System.out.print(row + " "); 
      } 

     System.out.println(); 
     }//end of main for loop 

    }//end of printPyramid 

    }//end of class 

我得到的錯誤,我無法弄清楚如何得到它正確地打印出來。 我相信方法搞砸了?

+2

你能發表你的錯誤嗎?如果你對此一無所知,那麼很難解決一個錯誤。 **和**是這個作業嗎? – elyashiv

+1

*我收到錯誤... *您有什麼錯誤? – Pigueiras

+0

請打破你的問題是具體的,顯示與任何相關的代碼和調試錯誤打破的單個功能/隔間 – Ozzy

回答

-1

這裏有兩個大錯誤。首先,與Java的所有是類,所以你必須把方法內的類。例如:

public class Anything { 
    public static void main ... 

    public static void printPyramid ... 
} 

第二個,你要調用主內的方法printPyramid,因爲如果不首先把它稱爲不會被執行。

public class Anything { 
    public static void main ... { 
     ... 
     printPyramid (numLines); 
     ... 
    } 

    public static void printPyramid ... 
} 

我希望這些小的跡象可以幫助你。

+0

非常感謝!我把它降低到只有1個錯誤... 'Pyramid.java:28:錯誤:類金字塔方法printPyramid不能應用於給定類型;' 'printPyramid();'' 要求:int' '發現:沒有參數' '原因:實際和形式參數列表長度不同' – user1368970

+0

@ user1368970這僅僅是一個例子,你必須用int作爲參數調用'printPyramid'。這個錯誤向你解釋:'required:int found:no arguments' – Pigueiras