Object-Oriented Programming with Java, part I – Exercise 99

This exercise prints stars, the number of which is equal to the value of cell in the array.

My Code

Main

public class Main {

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

    public static void printArrayAsStars(int[] array) {
        // write code here
        for (int i = 0; i < array.length; i++){
            for (int j = 0 ; j < array[i]; j++){
                System.out.print("*");
            }
            System.out.println("");
        }
    }
}

Model Code

Main

public class Main {

 

    public static void main(String[] args) {

        // test the method here

        int[] array = {5, 1, 3, 4, 2};

        printArrayAsStars(array);

    }

 

    public static void printArrayAsStars(int[] array) {

        // write code here

        for (int i = 0; i < array.length; i++) {

            int numberOfStars = array[i];

 

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

                System.out.print("*");

            }

 

            System.out.println();

        }

    }

}

Comments

I prefer mine to the model code as it doesn’t use an additional variable. In this case numberOfStars.

Leave a comment