class Playground code example

Example: class Playground

class Playground {
    /**
     * Implement method that takes array of ints and returns the 
     * smallest element of the array.
     * 
     * Example:
     *  findSmallestElement([0]) => 0
     *  findSmallestElement([1, 1, 1]) => 1
     *  findSmallestElement([-1, -4, -3, -2]) => -4
     */ 
    private static int findSmallestElement(int[] nums) {
        // WRITE YOUR CODE BELOW THIS LINE
        
        // WRITE YOUR CODE ABOVE THIS LINE
    }
    
    public static void main(String[ ] args) {
        test(findSmallestElement(new int[]{0}), 0, "arrayWithOneElement");
        test(findSmallestElement(new int[0]), 0, "emptyArray");
        test(findSmallestElement(new int[]{1, 1, 1, 1}), 1, "arrayWithSameElements");
        test(findSmallestElement(new int[]{1, 2, 3, 4}), 1, "arrayWithLargestElementInTheEnd");
        test(findSmallestElement(new int[]{1, 4, 3, 2}), 1, "arrayWithLargestElementInTheMiddle");
        test(findSmallestElement(new int[]{-1, -4, -3, -2}), -4, "arrayWithNegativeElements");
    }
    
    private static void test(int actual, int expected, String testName) {
        if (actual != expected) {
            String errorMessage = String.format(
                "Test %s failed: %s is not equal to expected %s",
                testName, 
                actual,
                expected);
            System.out.println("ERROR: " + errorMessage);  
        } else {
            System.out.println("SUCCESS: " + testName + " passed");
        }
    }
}

Tags:

Java Example