-2

次の出力を出力するネストされたforループを作成することになっています。

                   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

私は2つの方法を使用することになっています。

mainメソッドは、ユーザーから必要な行数を取得することだけを想定しています。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

エラーが発生し、正しく印刷する方法がわかりません。方法がめちゃくちゃだと思いますか?

4

1 に答える 1

-1

ここに2つの大きなエラーがあります。まず、Javaを使用するALLはクラスであるため、そのmainメソッドをクラス内に配置する必要があります。例えば:

public class Anything {
    public static void main ...

    public static void printPyramid ...
}

2つ目は、メイン内でメソッドを呼び出す必要がありますprintPyramid。これは、が最初に呼び出されないと実行されないためです。

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

    public static void printPyramid ...
}

この小さな兆候がお役に立てば幸いです。

于 2012-10-08T22:26:32.440 に答える