240 likes | 390 Views
CS 201 Lecture 9:. John Hurley Cal State LA. Variable Length Argument Lists. The number of parameters for a method is fixed in the method signature However, a method that takes an array parameter will accept an array of any length
E N D
CS 201 Lecture 9: John Hurley Cal State LA
Variable Length Argument Lists • The number of parameters for a method is fixed in the method signature • However, a method that takes an array parameter will accept an array of any length • Recall the command line parameters example; it prints out each String in args, regardless of how many Strings there are. • It is possible to send a variable number of values of the same type to a method by simply sending an array
Variable Length Argument Lists • There is also a shorthand used in method signatures for a variable number of parameters of the same type, which will be treated as an array. • public double myMethod(double… theNums){ • }
Variable Length Argument Lists public class Demo2 { public static void main(String[] args) { System.out.println(sumAll(0,0)); System.out.println(sumAll(0,1,2)); System.out.println(sumAll(0,1,2,3)); } public static int sumAll(int... numbers){ int total = 0; for(int i: numbers) total += i; return total; } }
JOptionPane.showOptionDialog • Lets user select an option • Uses an array of Strings for the choices, eg: • String[] choices = {"Quit", "Turnips", "Shoe Leather", "Brussels Sprouts"}; • Returns an int corresponding to the index of the user’s choice in the String array • int choice = JOptionPane.showOptionDialog(null, "Choose: ", "Main Menu", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices, null); • If the user chooses the first option, the return value is 0; if he chooses the second option, return value is 1, etc.
JOptionPane.showOptionDialog String[] choices = { "Quit", "Apple Pie", "Easy A", "Boot To The Head" }; int choice = JOptionPane.showOptionDialog(null, "Choose: ", "Main Menu", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices, null); JOptionPane.showMessageDialog(null, "you chose option # " + choice + " which is : " + choices[choice]);
JOptionPane.showOptionDialog • Here is the method signature • int showOptionDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon, Object[] options, Object initialValue) • Don’t bother memorizing all the parameters. Just start with an example each time and change it around. Look up the method in Oracle’s documentation if you want to find out the details of all these arguments
Two Dimensional Arrays • Java supports arrays of any number of dimensions • Just add an extra set of brackets and count: • int[][] twoD = new int[5][5]; • First subscript is the # of rows, second is the # of columns • This is actually implemented as an array of one-D arrays • You can declare and initialize a two dimensional array like this: • int[][] table ={{1,2,3},{2,4,6},{3,6,9}};
Two Dimensional Arrays public class TwoDArrayDemo{ public static void main(String[] args){ int rows = 6; int columns = 11; int[][] twoD = new int[rows][columns]; for(int x = 0; x < twoD.length; x++){ for(int y = 0; y < twoD[x].length; y++){ twoD[x][y] = x * y; } } for(int x = 0; x < twoD.length; x++){ System.out.println("\n"); for(int y = 0; y < twoD[x].length; y++){ System.out.print("\t" + twoD[x][y]); } } } }
Random Numbers • Random numbers are often useful in programming • Simulated data • Many games must be unpredictable • Security procedures may often work best with elements of randomness • Many algorithms (eg some sorts) are vulnerable to poor performance with certain patterns of data; can limit the risk by randomizing the data first • Computers can’t generate truly random numbers. Instead, we use algorithms that take seed numbers and generate series of numbers using calculations that generate patterns too complex to be easily predicted. • Seed numbers can be provided or supplied by checking the system clock.
Random Numbers • Random can generate random integers, doubles, or values of several other data types between 0 and a specified limit, using methods like nextInt(max) • import java.util.Random; • Most Random methods generate values using linear, not Gaussian, distributions.
Random Numbers public class Demo { private static int[] nums; public static void main(String[] args) { Random r = new Random(); nums = new int[50]; for (int counter = 0; counter < nums.length; counter++) nums[counter] = r.nextInt(100); Arrays.sort(nums); for (int i = 0; i < nums.length; i++) System.out.println(nums[i]); } }
Random Numbers We can also generate random Booleans. We might, for example, want to test a program using an array of Persons with randomly generated data including a field for whether or not the person is female. import java.util.Random; public class Demo { private static boolean[] bools; public static void main(String[] args) { Random r = new Random(); bools = new boolean[50]; for (int counter = 0; counter < bools.length; counter++) bools[counter] = r.nextBoolean(); for (int i = 0; i < bools.length; i++) System.out.println(bools[i]); } }
Random Numbers nextDouble() generates pseudorandom positive doubles less than 1 with to a uniform, not Gaussian, distribution: import java.util.Arrays; import java.util.Random; public class Demo { private static double[] nums; public static void main(String[] args) { Random r = new Random(); nums = new double[20]; for (int counter = 0; counter < nums.length; counter++) nums[counter] = r.nextDouble(); Arrays.sort(nums); for (int i = 0; i < nums.length; i++) System.out.println(nums[i]); System.out.println("\n\n"); } }
Random Numbers Typical output from the last example, after sorting: 0.07681127223863549 0.1318590535854024 0.2330592590007956 0.25464052363387923 0.2640736163976053 0.32197439909582426 0.43854538901010875 0.4638337286831462 0.6079744242031566 0.6223779767644768 0.6790583520295203 0.7471624033835046 0.7605374560296072 0.7687971599206234 0.8445071677493398 0.8566867924247004 0.8824308054110257 0.9594316339167386 0.9879688160797334
Random Numbers • nextGaussian() produces pseudorandom doubles with a normal distribution with mean = 0 and standard deviation 1. • You can change standard deviation by multiplying the value by the standard deviation you want, then change the mean by adding a constant (IN THAT ORDER!) • Normal distributions are often more useful than linear distributions for simulating real-world data
Random Numbers import java.util.Arrays; import java.util.Random; public class Demo { public static final double MEAN = 100; public static final double SDV = 10; private static double[] nums; public static void main(String[] args) { Random r = new Random(); nums = new double[40]; for (int counter = 0; counter < nums.length; counter++) nums[counter] = r.nextGaussian()*SDV + MEAN; Arrays.sort(nums); for (int i = 0; i < nums.length; i++) System.out.println(nums[i]); } }
Pseudocode • Algorithms are often described with pseudocode • Pseudo means “almost” or “fake” • Pseudocode uses various constructs that are common to many programming languages • Pseudocode is a way to abstract algorithms from the details of particular programming languages • Pseudocode is only pseudostandardized. You will see many different notations.
Pseudocode function factorial is:input: integer n such that n >= 0output: [n × (n-1) × (n-2) × … × 1] Iterative algorithm • create new variable called running_total with a value of 1 • begin loop • if n is 0, exit loop • set running_total to (running_total × n) • decrement n • repeat loop • return running_totalend factorial
Pseudocode Here is a different pseudocode format: procedure bizzbuzz for i := 1 to 100 do set print_number totrue; if i is divisible by 3 then print "Bizz"; set print_number tofalse; if i is divisible by 5 then print "Buzz"; set print_number tofalse; if print_number, print i; print a newline; end
Pseudocode Here is yet another format, this one more abstract: initialize passes to zero initialize failures to zero set minimum passing score to 70 set number of students to 10 for each student get the student's exam result from input if the student's score is greater than or equal to the passing score add one to passes else add one to failures print the number of passes print the number of failures if at least 70% of students passed print "The university is succeeding! Raise tuition!" else print "The university needs more resources! Raise tuition!"
Enum • Use Enum to create a data type that has a set of possible discrete values • Example: public enum Monster{ZOMBIE, VAMPIRE, DEMON, WEREWOLF}; • Enum names are capitalized because an enum defines a type, not a variable • Values are in all-caps because they are constants; each instance of the enum has one of these constant values
Enum • Define a variable of an enum type: Monster m = Monster.ZOMBIE; • Test whether a variable has a particular value: if(m == Monster.ZOMBIE) System.out.println(“Zombie approaching!”); • Use as method parameter: myMethod(Monster m){} • Send as argument: myMethod(Monster.ZOMBIE);
Extracting chars • Get the first char from a String. You may need to do this in Lab 8. String myString ="O Tanenbaum"; char myChar = myString.charAt(0); System.out.println(myChar);