簡體   English   中英

有沒有更干凈的方法來寫這個?

[英]Is there a cleaner way to write this?

我能夠從赫爾辛基 MOOC 課程中找出這個項目,但我認為有一種更簡潔、更易讀的方式來編寫它。 目標是打印出:

*****
*
***
****
**

以下是說明:“在名為“Printer”的 class 中完成方法 public static void print arrayInStars(int[] array) ,使其為數組中的每個數字打印一行星星。每行上的星星數量由數組中的相應數字定義。”

我的代碼如下所示:

public static void main(String[] args) {
    // You can test the method here
    int[] array = {5, 1, 3, 4, 2};

    printArrayInStars(array);
}

public static void printArrayInStars(int[] array) {
    // Write some code in here
    int i = 0;
    int o = 0;
    while (i < array.length) {

        while (o < array[i]) {
            System.out.print("*");
            o++;
        }

        i++;
        o = 0;
        System.out.println("");
    }
}

有沒有更優雅的方式來寫這個?

您的代碼沒有問題。 但是,由於您想要另一種方法,因此下面給出的是更緊湊的方法( 使用 for 循環):

public class Main {
    public static void main(String[] args) {
        int[] array = { 5, 1, 3, 4, 2 };
        printArrayInStars(array);
    }

    public static void printArrayInStars(int[] array) {
        for (int i = 0; i < array.length; i++) {
            for (int o = 0; o < array[i]; o++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Output:

*****
*
***
****
**

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM