/** Static methods showing off for-loops */ public class Examples { /** Prints out the loop counter the given number of times */ public static void simpleFor() { for(int ii = 0; ii <= 10; ii = ii+1) { System.out.println("Current value of ii = "+ii); } } /** Yields: number of chars in s that are digits */ public static int numDigits(String s) { int total = 0; // Holds the digit count for(int ii = 0; ii < s.length(); ii = ii + 1) { if (Character.isDigit(s.charAt(ii))) { total = total+1; } } return total; } /** Yields: copy of s with no blanks */ public static String noBlanks(String s) { String result = ""; // Holds the copy string for(int ii = 0; ii < s.length(); ii = ii + 1) { if (!Character.isWhitespace(s.charAt(ii))) { result = result+s.charAt(ii); } } return result; } /** Yields: “no integer in 2..n–1 divides n” * Precondition: n > 1 */ public static boolean isPrime(int n) { boolean result = true; for(int ii = 2; ii < n; ii = ii + 1) { if (n % ii == 0) { // ii "goes evenly" into n result = false; } } return result; } /** Yields: sum of squares of odd integers in the range m..n. */ public static int sumOfOddSquares(int m, int n) { int total = 0; for(int ii = m; ii < n; ii = ii + 1) { if (ii % 2 == 1) { // odd total = total + (ii*ii); } } return total; } }