Coding Samples
Write a function to reverse a string.
public static String reverse ( String s )
{
int length = s.length(), last = length − 1;
char[] chars = s.toCharArray();
for ( int i = 0; i < length/2; i++ )
{
char c = chars[i];
chars[i] = chars[last − i];
chars[last − i] = c;
}
return new String(chars);
}
Example output for "Madam, I'm Adam": madA m'I ,madaM
Write function to compute Nth fibonacci number:
static long fib(int n) { return n <= 1 ? n : fib(n-1) + fib(n-2); }
public static void main ( String[] args ) { for ( int i = 0; i < 10; i++ ) { System.out.print ( fib(i) + ", " ); } System.out.println ( fib(10) ); }
Test harness output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
Print out the grade-school multiplication table up to 12x12
public static void multTables ( int max ) { for ( int i = 1; i <= max; i++ ) { for ( int j = 1; j <= max; j++ ) { System.out.print ( String.format ( "%4d", j * i )); } System.out.println(); } }
Example output:
1 2 3 4 5 6 7 8 9 10 11 12 2 4 6 8 10 12 14 16 18 20 22 24 3 6 9 12 15 18 21 24 27 30 33 36 4 8 12 16 20 24 28 32 36 40 44 48 5 10 15 20 25 30 35 40 45 50 55 60 6 12 18 24 30 36 42 48 54 60 66 72 7 14 21 28 35 42 49 56 63 70 77 84 8 16 24 32 40 48 56 64 72 80 88 96 9 18 27 36 45 54 63 72 81 90 99 108 10 20 30 40 50 60 70 80 90 100 110 120 11 22 33 44 55 66 77 88 99 110 121 132 12 24 36 48 60 72 84 96 108 120 132 144
Write a function that sums up integers from a text file, one int per line.
public static void sumFile ( String name ) { try { int total = 0; BufferedReader in = new BufferedReader ( new FileReader ( name )); for ( String s = in.readLine(); s != null; s = in.readLine() ) { total += Integer.parseInt ( s ); } System.out.println ( total ); in.close(); } catch ( Exception xc ) { xc.printStackTrace(); } }
Write function to print the odd numbers from 1 to 99.
public static void printOdds() { for (int i = 1; i < 100; i += 2) { System.out.println ( i ); } }
Find the largest int value in an int array.
public static int largest ( int[] input ) { int max = Integer.MIN_VALUE; for ( int i = 0; i < input.length; i++ ) { if ( input[i] > max ) max = input[i]; } return max; }
Format an RGB value (three 1-byte numbers) as a 6-digit hexadecimal string.
public String formatRGB ( int r, int g, int b ) { return (toHex(r) + toHex(g) + toHex(b)).toUpperCase(); } public String toHex ( int c ) { String s = Integer.toHexString ( c ); return ( s.length() == 1 ) ? "0" + s : s; }
File I/O
public static void main(String args[]) throws Exception { FileReader fr = new FileReader("FileReaderDemo.java"); BufferedReader br = new BufferedReader(fr); String s; while((s = br.readLine()) != null) { System.out.println(s); } fr.close(); }