CSE 1341 - Honors Principles of Computer Science I
-
Upload
zenaida-english -
Category
Documents
-
view
17 -
download
0
description
Transcript of CSE 1341 - Honors Principles of Computer Science I
Note Set 10 Overview
ArraysArray ExamplesVariable-length argument lists
Example 1Declare an int array of length 20 and initialize each element
to the square of its subscript location.
int[] arr = new int [20];for (int i = 0; i < arr.length; i++) arr[i] = i * i;
Shuffle/Randomize the elements of an arrayRandomize the elements of the array arr from the previous
example
Random r = new Random();for (int i = 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;}
Rolling DiceUse an array and random number generator to count the
outcomes of rolling a pair of dice 10,000 times. Print the frequencies.
Random r = new Random();int[] frequency = new int[13];
for (int i = 0; i < 10000; i++) { frequency[ r.nextInt(11) + 2 ] ++;
System.out.println(“%s%10s\n”, “Total”, “Frequency”);
for (int i = 2; i < frequency.length; i++) System.out.printf(“%4d%10d\n”, i, frequency[i]);
Variable Length Argument ListsEver 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
public static double average(double... numbers) { double total = 0.0; for (double d : numbers) total += d; return total/numbers.length;
}
use the ellipsis to indicatevariable length argument
numbers acts like an array and can bemanipulated as such
Rules of Variable Length Argument Lists
parameter with ellipsis must be at the end of the parameter list
can only be one ellipsis in a parameter listpublic 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
public static double average(double... numbers)
Array IssuesArrays are statically sized
once they are declared, they cannot change sizeyou 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 ArrayOutOfBoundsremember 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.