80 likes | 188 Views
CSE 1341 - Honors Principles of Computer Science I. Spring 2008 Mark Fontenot mfonten@engr.smu.edu. Note Set 10. Note Set 10 Overview. Arrays Array Examples Variable-length argument lists. Example 1. int [] arr = new int [20]; for ( int i = 0; i < arr.length ; i ++)
E N D
CSE 1341 - HonorsPrinciples of Computer Science I Spring 2008 Mark Fontenot mfonten@engr.smu.edu Note Set 10
Note Set 10 Overview • Arrays • Array Examples • Variable-length argument lists
Example 1 int[] arr = new int [20]; for (inti = 0; i < arr.length; i++) arr[i] = i * i; Declare an int array of length 20 and initialize each element to the square of its subscript location.
Shuffle/Randomize the elements of an array Random r = new Random(); for (inti = 0; i < arr.length; i++){ int j = r.nextInt (arr.length); //swap element i with element j int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } Randomize the elements of the array arr from the previous example
Rolling Dice Random r = new Random(); int[] frequency = new int[13]; for (inti = 0; i < 10000; i++) { frequency[ r.nextInt(11) + 2 ] ++; System.out.println(“%s%10s\n”, “Total”, “Frequency”); for (inti = 2; i < frequency.length; i++) System.out.printf(“%4d%10d\n”, i, frequency[i]); Use an array and random number generator to count the outcomes of rolling a pair of dice 10,000 times. Print the frequencies.
Variable Length Argument Lists public static double average(double... numbers) { double total = 0.0; for (double d : numbers) total += d; return total/numbers.length; } use the ellipsis to indicate variable length argument numbers acts like an array and can be manipulated as such Ever notice that you can send 1, 2, 3, or more arguments to printf? It is possible to implement a method that takes a variable number of arguments
Rules of Variable Length Argument Lists public static double average(double... numbers) • parameter with ellipsis must be at the end of the parameter list • can only be one ellipsis in a parameter list • public static void foo(int... vals, int x, int y);//Don’t you dare! • public static void bar(int... vals, int… otherVals);//NO NO! • This is sometimes called a vararg for variable-length argument list
Array Issues • Arrays are statically sized • once they are declared, they cannot change size • you can allocate a new, larger array and copy the contents of the old array over. • can be computationally expensive especially for large array or if this function is performed often. • If you attempt to access past the end of an array, you’ll get a ArrayOutOfBounds • remember that x[i] is a reference to a memory location • so if you access an invalid subscript i the you would be trying to access memory you do not have access to OR the reference is NULL and thus can’t be accessed.