Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 John Hurley Cal State LA CS 201.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
CSCI 160 Midterm Review Rasanjalee DM.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
 2002 Prentice Hall. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Arrays Chapter 6 Chapter 6.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Random (1) Random class contains a method to generate random numbers of integer and double type Note: before using Random class, you should add following.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection Statement 4.6 if else Selection Statement 4.7 while.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
Java Unit 9: Arrays Declaring and Processing Arrays.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 6: Iteration Part 2. Create triangle pattern [] [][] [][][] [][][][] Loop through rows for (int i = 1; i
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Chapter 4: Loops and Files
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Lecture 5 Methods. Sometimes we want to perform the same sequence of operations multiple times in a program. While loops allow us to do this, they are.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure 4.6 The if / else Selection Structure 4.7.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
DT249-Information Systems Research Practice Programming Revision Lecture 2 Lecturer: Patrick Browne.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
Week 6 - Friday.  What did we talk about last time?  Loop examples.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
 2005 Pearson Education, Inc. All rights reserved Arrays.
Chapter 9 Introduction to Arrays Fundamentals of Java.
John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:
Lecture 11 CS201.
Lecture 3 Linear Search and Binary Search ArrayLists
Lecture 3 Lists Linear and Binary Search C Structs .jar files
Introduction to Programming
Dr. Sampath Jayarathna Cal Poly Pomona
Chapter 4 - Control Structures: Part 1
Suggested self-checks: Section 7.11 #1-11
Presentation transcript:

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved John Hurley Cal State LA CS 201 Lecture 9:

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 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){ }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 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; }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 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.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 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]);

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 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)Component ObjectStringIconObject 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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Two Dimensional Arrays 8 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}};

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Two Dimensional Arrays 9 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]); }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 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.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 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.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 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]); }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 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]); }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 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"); }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Random Numbers Typical output from the last example, after sorting:

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 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]); }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Pseudocode 18 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.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Pseudocode 19 function factorial is: input: integer n such that n >= 0 output: [n × (n-1) × (n-2) × … × 1] Iterative algorithm 1. create new variable called running_total with a value of 1 2. begin loop 1. if n is 0, exit loop 2. set running_total to (running_total × n) 3. decrement n 4. repeat loop 3. return running_total end factorial

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Pseudocode 20 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"; set print_number to false; if print_number, print i; print a newline; end

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Pseudocode 21 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!"

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 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);

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Extracting chars 24 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);