Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 11 CS201.

Similar presentations


Presentation on theme: "Lecture 11 CS201."— Presentation transcript:

1 Lecture 11 CS201

2 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

3 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){ }

4 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;

5 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.

6 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]);

7 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

8 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}};

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; } System.out.println("\n"); System.out.print("\t" + twoD[x][y]);

10 Two-Dimensional Arrays
public class TwoDArrayDemo{ public static void main(String[] args){ int rows = 8; int columns = 8; String[][] twoD = new String[rows][columns]; for(int rowCounter = 0; rowCounter < twoD.length; rowCounter++){ for(int colCounter = 0; colCounter < twoD[rowCounter].length; colCounter++){ twoD[rowCounter][colCounter] = "Row: " + rowCounter + " Col: " + colCounter ; } 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\t" + twoD[x][y] );

11 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 or some part of the algorithm 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.

12 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.

13 Random Numbers public static void main(String[] args) { }
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]); }

14 Random Numbers Random r = new Random(); bools = new boolean[50];
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]); }

15 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"); }

16 Random Numbers Typical output from the last example, after sorting:

17 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

18 Random Numbers Random r = new Random(); nums = new double[40];
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]); }

19 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.

20 Pseudocode function factorial is: input: integer n such that n >= 0 output: [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_total end factorial

21 Pseudocode Here is a different pseudocode format: procedure bizzbuzz for i := 1 to 100 do set print_number to true; if i is divisible by 3 then print "Bizz"; set print_number to false; if i is divisible by 5 then print "Buzz"; if print_number, print i; print a newline; end

22 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!" print "The university needs more resources! Raise tuition!"

23 Desk Check Desk checking or desk tracing is the technique of executing code manually, with paper and pencil. Trace table: a table used to keep track of data values during a desk check (example from Wikipedia) int i, x = 0; for (i = 1; i <= 10; i++) { x = i * 2; }

24 Data Structures Memorize This!
A data structure is a systematic way to organize information in order to improve the efficiency of algorithms that will use the data

25 Lists Need to import java.util.List as well as whatever specific type of list you use, eg java.util.ArrayList A List must be a list of values of some other data type, in the same way that an array is an array of items of some other type. List are parameterized by the data type of the values in the list. Unlike an array, a list can only contain objects, not primitive types. For example, you can not declare a list of doubles, but you can declare a list of Doubles. You will understand this better in a couple of weeks. We show the underlying data type by enclosing it in angle braces, for example: List <String>

26 List Methods The List interface provides many methods you will need to use with lists. Here are some easy to understand ones. add() adds an item to the end of the list get(int position) gets a reference to the item at the specified position in the list isEmpty() returns a boolean that indicates just what it sounds like size() shows the number of items in the list clear() deletes all items from the list

27 More List Methods package demos; import java.util.List;
import java.util.ArrayList; public class Demo { public static void main(String args[]) { // create the list List<String> myList = new ArrayList<String>(); // add items to the list myList.add("Andy"); myList.add("Barry"); myList.add("Cathy"); // print the items in the list for(String s: myList) System.out.println(s); System.out.println(); // add another item to the list, then print myList.add("Doug"); // delete an item from the list, then print myList.remove(0); } // end main() }

28 More List Methods Some List methods hinge on the fact that a List contains elements of some other data type. contains(Object o) indexOf(Object o) finds the index of the first occurrence of a value in the list lastIndexOf(Object o) finds the index of the last occurrence of a value in the list

29 Menu with Loop And Switch
It is very common for an application to give a user a menu of options within a loop that continues until the user chooses to quit: public class MenuLoopDemo { public static void main(String[] args){ MenuLoopDemo d = new MenuLoopDemo(); d.menu(); } public void menu(){ int choice = 0; String[] options = {"Quit", "EasyA", "Swift Kick"}; do{ choice = JOptionPane.showOptionDialog(null, "Choose One", "Please Select One", 2, choice, null, options, options); switch(choice){ case 1: easyA(); break; case 2: swiftKick(); } while(choice != 0); public void easyA(){ System.out.println("Easy A"); public void swiftKick(){ System.out.println("Swift Kick!");

30 .jar files .jar files are used for distributing Java applications and libraries. The file format is .zip, but the extension .jar identifies them as Java Archives They contain bytecode (.class files), any other files from the application or library (like images or audio files), and can also contain source code The JDK contains command line tools for making jar files, but this is easier to do with Eclipse Jar files may be executable, meaning that they are configured to launch the main() of some class contained in the jar Applications that will be distributed as runnable .jars usually have GUIs. If a user runs the .jar by double clicking on it in Windows Explorer, MacFinder, etc., he won’t see any command line I/O. In this course, don’t use command line i/o in labs that require runnable .jars.

31 .jar files

32 .jar files


Download ppt "Lecture 11 CS201."

Similar presentations


Ads by Google