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

This exercise prints out the contents of the array in a slightly nicer fashion with spaces and commas.

My Code

Main

public class Main {

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

    public static void printElegantly(int[] array) {
        // Write code here
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
            if (i < array.length - 1){
                System.out.print(", ");
            }
            
        }
    }
}

Model Code

Main

public class Main {

 

    public static void main(String[] args) {

        // test method here

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

        printElegantly(array);

    }

 

    public static void printElegantly(int[] array) {

        // Write code here

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

            System.out.print(array[i]);

            if (i < (array.length - 1)) {

                System.out.print(", ");

            }

        }

        System.out.println();

    }

Comments

Both my code and the model code are exactly the same.

Leave a comment