TestLargest.java Source code

Java tutorial

Introduction

Here is the source code for TestLargest.java

Source

import junit.framework.TestCase;

public class TestLargest extends TestCase {

    public TestLargest(String name) {
        super(name);
    }

    public void testOrder() {
        assertEquals(9, Largest.largest(new int[] { 9, 8, 7 }));
        assertEquals(9, Largest.largest(new int[] { 8, 9, 7 }));
        assertEquals(9, Largest.largest(new int[] { 7, 8, 9 }));
    }

    public void testEmpty() {
        try {
            Largest.largest(new int[] {});
            fail("Should have thrown an exception");
        } catch (RuntimeException e) {
            assertTrue(true);
        }
    }

    public void testOrder2() {
        int[] arr = new int[3];
        arr[0] = 8;
        arr[1] = 9;
        arr[2] = 7;
        assertEquals(9, Largest.largest(arr));
    }
}

class Largest {
    public static int largest(int[] list) {
        int index, max = Integer.MAX_VALUE;
        if (list.length == 0) {
            throw new RuntimeException("Empty list");
        }
        for (index = 0; index < list.length - 1; index++) {
            if (list[index] > max) {
                max = list[index];
            }
        }
        return max;
    }
}