// Example of class with methods, data, and object instantiation

public class Example {

    // Pool of characters
    String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_-";
    
    // Generate a random string
    public String randomString(int stringLength) {
        String random = new String();
        for (int i = 0; i < stringLength; i++) {
            int j = (int) (Math.random() * characters.length());
            random += characters.charAt(j);
        }
        return random;
    }
    
    // Example of method with no return value
    public void printLotsOfStuff(int numberLines) {
        for (int i = 0; i < numberLines; i++) {
            String r = randomString(50);
            System.out.println(r);
        }
    }
    
    // Example of method with return value
    public double power(double value, int power) {
        double result = 1.0;
        while (power-- > 0)
            result *= value;
        return result;
    }
    
    public static void main(String[] args) {

        // Instantiate object
        Example example = new Example();
        
        // Call method
        example.printLotsOfStuff(5);
        
        // Call method
        double value = 5.0;
        double squared = example.power(value, 2);
        double cubed = example.power(value, 3);
        double quadrupled = example.power(value, 4);
        System.out.println("value = " + value);
        System.out.println("squared = " + squared);
        System.out.println("cubed = " + cubed);
        System.out.println("quadrupled = " + quadrupled);
        System.out.println("quintupled = " + example.power(value, 5));
        double sextupled = example.power(value, 5) * value;
        System.out.println("sextupled = " + sextupled);
    }
}

© 2014 CS160 Colorado State University. All Rights Reserved.