Announcements & Review Last Time: More on input: Scanner class While loops Today more on While Methods in a class Declarations Parameters Announcements Lab 2 Due Thursday 10pm 1 file per pair Lecture 8: Simple Methods
Lecture 8: Simple Methods When do we while? boolean condition = true; // keep doing the loop while condition==true while (condition) { …. // somewhere in the loop the condition // becomes false. Why? if (test) { condition = false; } Lecture 8: Simple Methods
Reading Input Features String word1 = stdin.next(); int number1 = stdin.nextInt(); double dnum1 = stdin.nextDouble(); boolean progress1 = stdin.nextBoolean(); // peeking to make sure the format is right boolean isString = stdin.hasNext(); boolean isInt = stdin.hasNextInt(); boolean isDouble = stdin.hasNextDouble(); boolean isBoolean = stdin.hasNextBoolean(); Lecture 8: Simple Methods
Lecture 8: Simple Methods BlueJ Examples Lecture 8: Simple Methods
Why Methods? Algorithmic Thinking… Divide the program up in logical parts Analogs book with chapters; recipes; laundry Laundry Every Sunday collect dirty clothes sort into color piles (& a really dirty pile!) wash each pile dry each pile fold each pile & sort by person put them up Lecture 8: Simple Methods
Why Methods? Algorithmic Thinking… Distinct logical function organization gather, sort, wash, dry, fold, sort, put up Reuse - repetition … every week Parameterize - things that change sort differs every week number of piles, drawers, etc. Lecture 8: Simple Methods
Lecture 8: Simple Methods Reuse // public - any code can use this class // class - defines a type of object, Shapes public class Shapes { // instance variables - persistent class state // ...more on this later… /** * Constructor for objects of class Shapes */ public Shapes() { // initialize instance variables } Lecture 8: Simple Methods
Lecture 8: Simple Methods Reuse public class Shapes { // methods in this class - logical, reusable & // parameterized units // this method: its name is printBox // public - any code with a Shape object can call // printBox on object, e.g., object.printBox // private - only other Shape methods can call it // void - returns nothing public void printBox() { … } Lecture 8: Simple Methods
Lecture 8: Simple Methods BlueJ Examples Lecture 8: Simple Methods
Lecture 8: Simple Methods More Questions? Lecture 8: Simple Methods