Java loops.


public class Loops {
	public static void main(String [] args) {
		int n = 10;
		int i = 0;
		// a very boring loop: just prints numbers in order
		while (i <= n) {
			System.out.print(i + " ");
			i = i + 1;
		}
		System.out.println(); // go to a new line 
		
		// write a loop to print the numbers from 10 to 0 
		// in decreasing order
		
		i = n; 
		while (i >= 0) {
			System.out.print(i + " ");
			i = i - 1;			
		}
		System.out.println(); // go to a new line 
		
		// same thing as a 'while' loop
		for(i = 0; i <= n; i++) { //i++ is a shortcut for i = i + 1
			System.out.print(i + " ");
		}
		System.out.println(); 
			
		printDecreasing(n);
		
		String str = "aardvarks don't eat bananas";
		
		int count = countA(str);
		
		System.out.println(str + " has " + count + " letters a");
		
		System.out.println("strawberry" + " has " + countA("strawberry") + " letters a");
	}
	
	public static void printDecreasing(int n) {
		// write a 'for' loop to print the numbers from 10 to 0 
		// in decreasing order
		for(int i = n; i >= 0; i--) { 
			System.out.print(i + " ");
		}
		System.out.println(); 	
	}
	
	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.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.