Java methods: introduction.


public class LoopsMethods {
	public static void main(String[] args) {

		printNumbers(1, 10, 2);
		printNumbers(-10, 0, 1);

		String str = "aardvarks don't eat bananas";

		System.out.println("The string \"" + str + "\" has " + countA(str)
				+ " letters a");

	}

	/**
	 * Parameters: three integers: start, bound, and skip. The method prints
	 * numbers starting at start, no larger than bound, incrementing by skip.
	 * The numbers are printed on a single line, then a new line is printed.
	 **/
	public static void printNumbers(int start, int bound, int skip) {
		for (int i = start; i <= bound; i = i + skip) {
			System.out.print(i + " ");
		}
		System.out.println();
	}

	/**
	 * Parameters: String s. The method takes a String and returns the number of
	 * lower-case letters 'a' in the string.
	 **/
	public static int countA(String s) {
		int count = 0;
		for (int j = 0; j < s.length(); j++) {
			if (s.charAt(j) == 'a') {
				count++;
			}
		}
		return count;
	}
}

CSci 2101 course web site.