Layouts, Types, & Switches Copyright © 2012 Pearson Education, Inc.

Slides:



Advertisements
Similar presentations
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Advertisements

Enumerated Types Define a new data type and list all possible values: enum Season {winter, spring, summer, fall} Then the new type can be used to declare.
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Logical Operators and Conditional statements
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Switch Statements Comparing Exact Values. 2 The Switch Statement The switch statement provides another way to decide which statement to execute next The.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing.
Copyright © 2014 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design 8 th Edition John.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Chapter 5 Loops.
Flow of Control Part 1: Selection
Chapter 7 Object-Oriented Design Concepts
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Switch Statements Comparing Exact Values. The Switch Statement: Syntax The switch statement provides another way to decide which statement to execute.
1 Chapter 3 Selections. 2 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Programming in Java (COP 2250) Lecture 8 Chengyong Yang Fall, 2005.
Chapter 6. else-if & switch Copyright © 2012 Pearson Education, Inc.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 M.A. Papalaskari, Villanova University Everyday objects: Strings and Wrappers CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/29 The switch Statement The switch statement provides another way.
Topics Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement The for loop Nested Loops.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Control statements Mostafa Abdallah
Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images.
Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Wrapper Classes Use wrapper objects in Collections when you can’t use primitive types Primitive TypeWrapper Class byteByte shortShort intInteger longLong.
1 More about Flow of Control. Topics Debugging Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
© 2004 Pearson Addison-Wesley. All rights reserved5-1 The if-else Statement An else clause can be added to an if statement to make an if-else statement.
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
© 2004 Pearson Addison-Wesley. All rights reserved January 27, 2006 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Information and Computer Sciences University of Hawaii, Manoa
Project 1.
Chapter 6 More Conditionals and Loops
Chapter 6 More Conditionals and Loops
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
Chapter 6 More Conditionals and Loops
Chapter 6 More Conditionals and Loops
CprE 185: Intro to Problem Solving (using C)
Arrays October 6, 2006 ComS 207: Programming I (in Java)
Midterm Review October 23, 2006 ComS 207: Programming I (in Java)
Comparing Data & the ‘switch’ Statement
Outline Software Development Activities
Comparing Data & the ‘switch’ Statement
Chap 7. Advanced Control Statements in Java
Conditionals and Loops
CprE 185: Intro to Problem Solving (using C)
Presentation transcript:

Layouts, Types, & Switches Copyright © 2012 Pearson Education, Inc.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling GUI Principles Components: GUI building blocks –Buttons, menus, sliders, etc. Layout: arranging components to form a usable GUI –Using layout managers. Events: reacting to user input –Button presses, menu selections, etc.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Elements of a frame Title Menu bar Content pane Window controls

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Layout managers Manage limited space for competing components (like our content pane) –FlowLayout, BorderLayout, GridLayout, BoxLayout, GridBagLayout. Manage Container objects, e.g. a content pane Each imposes its own style

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling FlowLayout

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling BorderLayout

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling GridLayout

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling BoxLayout Note: no component resizing.

GridBagLayout Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling A message dialog private void showAbout() { JOptionPane.showMessageDialog(frame, "ImageViewer\n" + VERSION, "About ImageViewer", JOptionPane.INFORMATION_MESSAGE); } private void showAbout() { JOptionPane.showMessageDialog(frame, "ImageViewer\n" + VERSION, "About ImageViewer", JOptionPane.INFORMATION_MESSAGE); }

Layout Example: Box vs Border Copyright © 2012 Pearson Education, Inc.

Layout Example: Box vs Border Copyright © 2012 Pearson Education, Inc.

Types Revisited Copyright © 2012 Pearson Education, Inc.

Wrapper Classes Use wrapper objects in Collections when you can’t use primitive types Primitive TypeWrapper Class byteByte shortShort intInteger longLong floatFloat doubleDouble charCharacter booleanBoolean

Wrapper Classes For example: Integer age = new Integer(40); Wrapper classes contain static methods to convert between types. For example, to convert a String to an int : int num = Integer.parseInt(str); Wrapper classes also contain constants such as MIN_VALUE and MAX_VALUE in the Integer class, which hold the smallest and largest int values Copyright © 2012 Pearson Education, Inc.

Enumerated Types Define a new data type and list all possible values: enum Season {winter, spring, summer, fall} Then the new type can be used to declare variables Season time; And then the variable can be assigned a value: time = Season.fall; The only values this variable can be assigned are the ones from the enum definition Copyright © 2012 Pearson Education, Inc. Why would we want to use enums?

Enumerated Types An enumerated type definition can be more interesting than a simple list of values Because they are like classes, we can add additional instance data and methods We can define an enum constructor as well Each value listed for the enumerated type calls the constructor See Season.java See SeasonTester.java Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // Season.java Author: Lewis/Loftus // // Enumerates the values for Season. //******************************************************************** public enum Season { winter ("December through February"), spring ("March through May"), summer ("June through August"), fall ("September through November"); private String span; // // Constructor: Sets up each value with an associated string. // Season (String months) { span = months; } // // Returns the span message for this value. // public String getSpan() { return span; }

Copyright © 2012 Pearson Education, Inc. //******************************************************************** // SeasonTester.java Author: Lewis/Loftus // // Demonstrates the use of a full enumerated type. //******************************************************************** public class SeasonTester { // // Iterates through the values of the Season enumerated type. // public static void main (String[] args) { for (Season time : Season.values()) System.out.println (time + "\t" + time.getSpan()); }

Copyright © 2012 Pearson Education, Inc. //******************************************************************** // SeasonTester.java Author: Lewis/Loftus // // Demonstrates the use of a full enumerated type. //******************************************************************** public class SeasonTester { // // Iterates through the values of the Season enumerated type. // public static void main (String[] args) { for (Season time : Season.values()) System.out.println (time + "\t" + time.getSpan()); } Output winterDecember through February springMarch through May summerJune through August fallSeptember through November

Enumerated Types Every enumerated type contains a static method called values that returns a list of all possible values for that type The list returned from values can be processed using a for-each loop An enumerated type cannot be instantiated outside of its own definition A carefully designed enumerated type provides a versatile and type-safe mechanism for managing data Copyright © 2012 Pearson Education, Inc.

else-if & switch Copyright © 2012 Pearson Education, Inc.

Example: else-if Copyright © 2012 Pearson Education, Inc. int grade = 85; char letter = ‘’; if (grade > 89) letter = ‘A’; else if (grade > 79) letter = ‘B’; else if (grade > 69) letter = ‘C’; else if (grade > 59) letter = ‘D’; else letter = ‘F’; int grade = 85; char letter = ‘’; if (grade > 89) letter = ‘A’; else if (grade > 79) letter = ‘B’; else if (grade > 69) letter = ‘C’; else if (grade > 59) letter = ‘D’; else letter = ‘F’;

The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to statement associated with the first case value that matches Copyright © 2012 Pearson Education, Inc.

The switch Statement The general syntax of a switch statement is: switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case... } switch and case are reserved words If expression matches value2, control jumps to here Copyright © 2012 Pearson Education, Inc. A break statement can be used in a switch to jump to the end of the switch statement

The switch Statement switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; } An example of a switch statement: Copyright © 2012 Pearson Education, Inc.

Example: else-if vs switch Copyright © 2012 Pearson Education, Inc. int grade = 85; char letter = ‘’; if (grade > 89) letter = ‘A’; else if (grade > 79) letter = ‘B’; else if (grade > 69) letter = ‘C’; else if (grade > 59) letter = ‘D’; else letter = ‘F’; int grade = 85; char letter = ‘’; if (grade > 89) letter = ‘A’; else if (grade > 79) letter = ‘B’; else if (grade > 69) letter = ‘C’; else if (grade > 59) letter = ‘D’; else letter = ‘F’; int grade = 85; char letter = ‘’; switch (grade) { case 100: case 99: case 98: … case 90: letter = ‘A’; break; case 89: … default: letter = ‘F’; } int grade = 85; char letter = ‘’; switch (grade) { case 100: case 99: case 98: … case 90: letter = ‘A’; break; case 89: … default: letter = ‘F’; } If no other case value matches, the optional default case will be executed (if present)

The switch Statement The type of a switch expression must be integers, characters, or enumerated types Why? == Copyright © 2012 Pearson Education, Inc. As of Java 7, a switch can also be used with strings You cannot use a switch with floating point values The implicit boolean condition in a switch statement is equality You cannot perform relational checks with a switch statement (i.e., > or <)

Copyright © 2012 Pearson Education, Inc. //******************************************************************** // GradeReport.java Author: Lewis/Loftus // // Demonstrates the use of a switch statement. //******************************************************************** import java.util.Scanner; public class GradeReport { // // Reads a grade from the user and prints comments accordingly. // public static void main (String[] args) { int grade, category; Scanner scan = new Scanner (System.in); System.out.print ("Enter a numeric grade (0 to 100): "); grade = scan.nextInt(); category = grade / 10; System.out.print ("That grade is "); continue

Copyright © 2012 Pearson Education, Inc. continue switch (category) { case 10: System.out.println ("a perfect score. Well done."); break; case 9: System.out.println ("well above average. Excellent."); break; case 8: System.out.println ("above average. Nice job."); break; case 7: System.out.println ("average."); break; case 6: System.out.println ("below average. You should see the"); System.out.println ("instructor to clarify the material " + "presented in class."); break; default: System.out.println ("not passing."); } Sample Run Enter a numeric grade (0 to 100): 91 That grade is well above average. Excellent.

Templates While Loop Index Template: initialize index while (condition){ statements to be repeated update index } For Loop Template: for(initialize index; condition; update index){ statements to be repeated } For Each Loop Template: for (ElementType elementName : collection){ statements to be repeated } While Loop Sentinel Template: get input value while (input != end condition){ statements to be repeated get input value } Example switch: switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; }

The Conditional Operator The conditional operator evaluates to one of two expressions based on a boolean condition Its syntax is: condition ? expression1 : expression2 If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated The value of the entire conditional operator is the value of the selected expression Example: char pf = grade > 59 ? ‘P’ : ‘F’; Copyright © 2012 Pearson Education, Inc.

The Conditional Operator The conditional operator is similar to an if-else statement, except that it is an expression that returns a value For example: larger = ((num1 > num2) ? num1 : num2); If num1 is greater than num2, then num1 is assigned to larger ; otherwise, num2 is assigned to larger The conditional operator is ternary because it requires three operands Copyright © 2012 Pearson Education, Inc.

The Conditional Operator Another example: If count equals 1, the "Dime" is printed If count is anything other than 1, then "Dimes" is printed System.out.println ("Your change is " + count + ((count == 1) ? "Dime" : "Dimes")); Copyright © 2012 Pearson Education, Inc.

Quick Check Copyright © 2012 Pearson Education, Inc. Express the following logic in a succinct manner using the conditional operator. if (val <= 10) System.out.println("It is not greater than 10."); else System.out.println("It is greater than 10."); System.out.println("It is" + ((val <= 10) ? " not" : "") + " greater than 10.");

The do Statement A do statement has the following syntax: do { statement-list; } while (condition); The statement-list is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false Copyright © 2012 Pearson Education, Inc.

Logic of a do Loop true condition evaluated statement false Copyright © 2012 Pearson Education, Inc.

The do Statement An example of a do loop: The body of a do loop executes at least once See ReverseNumber.java int count = 0; do { count++; System.out.println (count); } while (count < 5); Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // ReverseNumber.java Author: Lewis/Loftus // // Demonstrates the use of a do loop. //******************************************************************** import java.util.Scanner; public class ReverseNumber { // // Reverses the digits of an integer mathematically. // public static void main (String[] args) { int number, lastDigit, reverse = 0; Scanner scan = new Scanner (System.in); continue

Copyright © 2012 Pearson Education, Inc. continue System.out.print ("Enter a positive integer: "); number = scan.nextInt(); do { lastDigit = number % 10; reverse = (reverse * 10) + lastDigit; number = number / 10; } while (number > 0); System.out.println ("That number reversed is " + reverse); } Sample Run Enter a positive integer: 2896 That number reversed is 6982

Comparing while and do statement true false condition evaluated The while Loop true condition evaluated statement false The do Loop Copyright © 2012 Pearson Education, Inc.

Create a CeilingFan Class Step 1: Create the class, fields, & constructors –Add a Speed enum {off, low, medium, high} –Store the fan’s current speed –Create a default constructor Step 2: Create the following methods –changeSpeed that changes the speed w/ no parameters using a switch statement –changeSpeed with 1 parameter (the number of times to change it) that uses the first changeSpeed() method & a loop