請設計static void printStars()方法

請設計static void printStars()方法,傳入共幾列的參數,可以顯示下列星號字元的星角型,如下圖所示:

----------*

---------* *

--------* * *

-------* * * *

------* * * * *

-----* * * * * *

----* * * * * * *

---不顯示

請用for迴圈寫

若要讓(1)正三角變倒三角

(2)變正方形

(3)變一直線

分別該怎麼做呢??

問題有點多...

希望會得大大能幫忙解答

感謝!

1 Answer

Rating
  • 9 years ago
    Favorite Answer

    public class Run_1 {

    public void printTriangle(int a) {

    for (int i = 0; i < a; i++) {

    for (int k = i; k <= a; k++) {

    System.out.print(" ");

    }

    for (int j = 0; j <= i; j++) {

    System.out.print("* ");

    }

    System.out.println();

    }

    }

    public void printUnTriangle(int a) {

    for (int i=0; i<a; i++) {

    for (int k = 0; k <= i; k++) {

    System.out.print(" ");

    }

    for(int j=i; j<a; j++){

    System.out.print("* ");

    }

    System.out.println();

    }

    }

    public void printSquare(int a) {

    if (a == 1) {

    System.out.println("*");

    }else{

    for (int i = 0; i < a; i++) {

    System.out.print("*");

    }

    System.out.println();

    for (int i = 0; i < a - 2; i++) {

    System.out.print("*");

    for (int j = 0; j < a - 2; j++) {

    System.out.print(" ");

    }

    System.out.println("*");

    }

    for (int i = 0; i < a; i++) {

    System.out.print("*");

    }

    }

    }

    public void printLine(int a) {

    for(int i=0; i<a; i++){

    System.out.print("*");

    }

    }

    public static void main(String[] arge) {

    Scanner sc = new Scanner(System.in);

    Run_1 run = new Run_1();

    int tmp,r;

    System.out.print("請輸入 列 : ");

    tmp = sc.nextInt();

    System.out.print("1.正方形 2.正三角 3.倒三角 4.線: ");

    r = sc.nextInt();

    switch(r){

    case 1:

    run.printSquare(tmp);

    break;

    case 2:

    run.printTriangle(tmp);

    break;

    case 3:

    run.printUnTriangle(tmp);

    break;

    case 4:

    run.printLine(tmp);

    }

    }

    }

Still have questions? Get your answers by asking now.