M C6java5
Upcoming SlideShare
Loading in...5
×
 

M C6java5

on

  • 951 views

 

Statistics

Views

Total Views
951
Views on SlideShare
951
Embed Views
0

Actions

Likes
0
Downloads
3
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

M C6java5 M C6java5 Presentation Transcript

  • Simple Control Structures boolean s, the if statement switch-case
  • What are control structures?
    • You can’t do very much if your program consists of just a list of commands to be done in order
      • The program cannot choose whether or not to perform a command
      • The program cannot perform the same command more than once
      • Such programs are extremely limited!
    • Control structures allow a program to base its behavior on the values of variables
  • boolean
    • boolean is one of the eight primitive types
      • boolean s are used to make yes/no decisions
      • All control structures use booleans
    • There are exactly two boolean values, true (“yes”) and false (“no”)
      • boolean , true , and false are all lowercase
    • boolean s are named after George Boole, the founder of Boolean logic
    View slide
  • Declaring boolean variables
    • boolean variables are declared like any other kind of variable:
      • boolean hungry;
      • boolean passingGrade;
      • boolean taskCompleted = false;
    • boolean values can be assigned to boolean variables:
      • taskCompleted = true;
    View slide
  • Numeric comparisons
    • The following numeric comparisons each give a boolean result:
      • x < y // is x less than y?
      • x <= y // is x less than or equal to y?
      • x == y // is x equal to y? (do not use =)
      • x != y // is x unequal to y?
      • x >= y // is x greater than or equal to y?
      • x > y // is x greater than y?
    • Reminder: Don’t use == or != for floating-point numbers
  • The if statement
    • The if statement has the form:
      • if ( boolean-expression ) statement
    • Examples:
      • if (passingGrade) System.out.println(&quot;Whew!&quot;);
      • if (x > largest) largest = x;
      • if (citBook.price < 40.00) citBook.purchase();
    • The if statement controls one other statement
      • Often this isn’t enough; we want to control a group of statements
  • Compound statements
    • We can use braces to group together several statements into one “compound” statement:
      • { statement ; statement ; ...; statement ; }
    • Braces can group any number of statements:
      • { } // OK--this is an “empty” statement
      • { x = 0; } // OK--braces don’t hurt
      • { temp = x; x = y; y = temp; } //typical use
    • The compound statement is the only kind of statement that does not end with a semicolon
  • The if statement again
    • The if statement controls one other statement, but it can be a compound statement
    • Example:
      • if (cost < amountInPocket) { System.out.println(&quot;Spending $&quot; + cost); amountInPocket = amountInPocket - cost; }
    • It’s good style to use braces even if the if statement controls only a single statement:
      • if (cost > amountInPocket) { System.out.println(&quot;You can't afford it!&quot;); }
    • I personally make an exception to this style rule when the controlled statement fits easily on the same line with the if :
      • if (x < 0) x = -x; // use absolute value of x
  • Flowchart for the if statement condition? statement true false
  • The if-else statement
    • The if-else statement chooses which of two statements to execute
    • The if-else statement has the form:
      • if ( condition ) statement-to-execute-if-true ; else statement-to-execute-if-false ;
    • Either statement (or both) may be a compound statement
    • Notice the semicolon after each controlled statement
  • Example if-else statements
    • if (x >= 0) absX = x; else absX = -x;
    • if (itemCost <= bankBalance) { writeCheck(itemCost); bankBalance = bankBalance - itemCost; } else { callHome(); askForMoreMoney(2 * itemCost); }
  • Flowchart for the if-else statement condition? true statement-1 statement-2 false
  • Aside: the “mod” operator
    • The modulo, or “mod,” operator returns the remainder of an integer division
    • The symbol for this operation is %
    • Examples:
      • 57 % 10 gives 7
      • 20 % 6 gives 2
    • Useful rule: x is divisible by y if x % y == 0
    • If the left operand is negative, the result is negative (or zero)
      • Examples: -20 % 3 = -2 , 20 % -3 = 2 , -20 % -3 = -2
  • Nesting if (or if-then ) statements
    • A year is a leap year if it is divisible by 4 but not by 100, unless it is also divisible by 400
    • if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) leapYear = true; else leapYear = false; } else leapYear = true; } else leapYear = false;
  • Operations on boolean s
    • Assume p and q are booleans
    • There are four basic operations on booleans:
      • Negation (“not”): !p is true if p is false (and false otherwise)
      • Conjunction (“and”): p && q is true if both p and q are true
      • Disjunction (“or”): p || q is true if either of p and q is true
      • Exclusive or (“xor”): p ^ q is true if just one of p and q is true
  • Simpler tests
    • A simpler leap-year test:
      • if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) leapYear = true; else leapYear = false;
    • An even simpler leap-year test:
      • leapYear = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
  • The if-else statement
    • The if-else statement chooses which of two statements to execute
    • The if-else statement has the form:
      • if ( condition ) statement-to-execute-if-true ; else statement-to-execute-if-false ;
    • Either statement (or both) may be a compound statement
    • Notice the semicolon after each statement
    • The else part is optional
  • Dangling Else
    • Compiler cannot determine which “if” an “else” belongs to if there are no braces
      • String password = Keyboard.readString();
      • if (password.equals (realPassword))
      • if (name.equals (“admin”))
    • loggedIn = superPrivileges = true;
    • else
    • System.out.println (“Error”);
    • Java matches else with last unfinished if
    • Moral: Use shortcuts at your own risk – or don’t !
  • Multiway selection
    • Multiple conditions, each of which causes a different block of statements to execute
    • Can be used where there are more than 2 options
      • if ( condition1 )
      • {
      • statements …
      • }
      • else
      • {
      • if ( condition2 )
      • {
      • statements …
      • }
      • else
      • }
  • “ if” ladder
    • Just a nicer way to write multiway selection
    • if (operation == ‘a’)
    • {
    • answer = first + second;
    • }
    • else if (operation == ‘s’)
    • {
    • answer = first – second;
    • }
    • else if (operation == ‘m’)
    • {
    • answer = first * second;
    • }
  • The “switch” statement
    • Selects among different statements based on a single integer or character expression
    • Each set of statements starts in “case” and ends in “break” because switch does not use {}s
      • break passes control to statement immediately after switch
    • “ default” applies if none of the cases match
  • Sample switch statement
    • switch (SouperSandwichOrder)
    • {
    • case 1 : cheese = 1;
    • break;
    • case 2 : cheese = 1;
    • tomato = 1;
    • break;
    • case 3 : cheese = 1;
    • tomato = 1;
    • chukka = 1;
    • break;
    • default : cheese = 1;
    • break;
    • }
  • “ break” optimisation
    • If break is omitted, control continues to next statement in the switch
    • switch (SouperSandwichOrder)
    • {
    • case 3 : chukka = 1;
    • case 2 : tomato = 1;
    • case 1 :
    • default : cheese = 1;
    • }
  • Characters in “switch”
    • char Operation = Keyboard.readChar (“What to do?”);
    • switch (Operation)
    • {
    • case ‘a’ : answer = a + b;
    • break;
    • case ‘s’ : answer = a – b;
    • break;
    • case ‘m’ : answer = a * b;
    • break;
    • case ‘d’ : if (b != 0)
    • {
    • answer = a / b;
    • break;
    • }
    • default : answer = 0;
    • System.out.println (“Error”);
    • break;
    • }
  • Boolean operators ! || && Java true if parameter is false; false if parameter is true; NOT true if at least one parameter is true OR true if both parameters are true AND Meaning Boolean Algebra
  • Operator precedence
    • Now that we have seen how operators can be mixed, we need precedence rules for all operators
      • () (highest precedence – performed first)
      • !
      • * / %
      • + -
      • < <= > >=
      • == !=
      • &&
      • ||
      • = (lowest precedence – performed last)
  • Reversing expressions
    • Use ! operator to reverse meaning of boolean expression, e.g.,
      • if (mark >= 0)
      • {
      • // do nothing
      • }
      • else
      • System.out.println (“Error”);
    • Instead, invert the condition
      • if (! (mark >= 0))
      • System.out.println (“Error”);
    • Can we do better ?
  • Afvinkopdracht 5: Tic-tac-toe
  • Graphic programming The GUI revisited
    • Java, unlike C & C++, has standard packages for graphics
    • 2 related packages and sub-packages support graphics in Java
      • java.awt ( A bstract W indows T oolkit)
      • javax.swing
    • AWT is ‘peer-based’
      • Depends on graphical elements native local platform’s graphics system
      • Unix/Windows graphical programs written using AWT will have a different ‘look and feel’
    • Swing is much more platform independent
      • Graphical components are pre-built and are simply painted onto windows
      • Relies less on the underlying runtime environment
      • Usually slower than AWT-based programs
    • In practice graphical programs are a mixture of Swing and AWT classes
      • AWT takes care of all of the event handling for GUI’s (see later)
  • Frames
    • A frame is a top level window which is a container for graphical components (canvas, buttons, menus etc)
    • The AWT has a Frame class and Swing has a JFrame class
    • The following program displays an empty frame
  • import javax.swing.*; class MyFrame extends JFrame { public MyFrame() { setTitle(&quot;My first graphics program&quot;); setSize(400,300); } } public class FrameTest { public static void main(String[] args) { JFrame frame=new MyFrame(); frame.show(); } }
  •  
    • A class MyFrame is defined which is a sub-class of JFrame
      • A title is added
      • The frame is sized to 400x300 (by default, a frame is 0x0)
    • The frame is created by a call to the constructor
    • The frame is displayed by a call to JFrame.show()
      • This creates a separate thread which runs until the program is terminated – the main thread terminates
  • Swing inheritance hierarchy
    • The JFrame class inherits attributes from higher level container classes
      • Typically for resizing and positioning frames
    • Class names beginning with ‘J’ are Swing classes – everything else is part of AWT
  • JFrame JComponent JPanel … .. Component Frame Window Container
    • Most swing components (for example JPanel) are derived from the JComponent class
    • JFrame, being a top level window, is derived from the Window class
    • Other top level windows include JApplet and JDialog
  • Displaying graphics in frames – panels
    • Frames are containers – they can contain other user interface/graphical components
    • A frame contains a content pane into which components can be added
    • The following code is typical
    Container contentPane=frame.getContentPane(); Component c= ….; // UI or graphical component contentPane.add (c); // Add to the frame
  • Content pane Frame JPanel SomeText JField
  • Panels
    • Panels ( JPanel class) are added to the content pane
    • Panels are themselves containers
      • The can contain other UI components
      • They also have a surface onto which graphics can be drawn
        • Text
        • Basic shapes (lines, boxes etc)
        • Images
  • Drawing on panels
    • The paintComponent() method in JComponent (a superclass of JPanel ) must be overridden
    • paintComponent() is called automatically when the window has to be drawn or redrawn – for example when it is moved by the user. It is also called when the repaint() method of a panel is called
    • The following code creates a class MyPanel into which graphics can be drawn
    class MyPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); // Code placed here to draw graphics } }
    • The Graphics object defines the graphics context (fonts, line styles, colours etc)
    • A call to super.paintComponent() calls the paintComponent() method in JComponent (the base class of JPanel )
      • This call sets up the graphics context and performs other complex tasks
  • Displaying text in graphics windows
    • Text can be drawn onto panels using the Graphics.drawString() method
    • The text font and size can be optionally set/reset
    • The following program draws a string onto a panel
      • The panel is then added to a frame which is then displayed using JFrame.show()
  • import javax.swing.*; import java.awt.*; public class MyPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString(&quot;Hello there!&quot;,150,125); } }
  • import java.awt.event.*; import javax.swing.*; import java.awt.*; public class HelloFrame extends JFrame { public HelloFrame() { setTitle(&quot;Drawing a string example&quot;); setSize(400,300); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); Container contentPane=getContentPane(); contentPane.add(new MyPanel()); } }
  • public class FrameTest { public static void main(String[] args) { JFrame frame=new HelloFrame(); frame.show(); } }
  •  
    • Text fonts can be set/reset
      • The existing font applies until it is reset
    • The following code sets a bold Helvetica font with a larger font size
    public class MyPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); Font f=new Font(“Helvetica”,Font.BOLD,25); g.setFont(f); g.drawString(&quot;Hello there!&quot;,150,125); } }
  •  
  • Drawing simple graphics
    • Class java.awt.Graphics contains methods which allow simple graphics to be drawn in different colours
    • Graphics.setcolor() sets the drawing colour
      • Colour is represented by the class java.awt.Color(int red, int blue, int green) defining the RGB components
      • Preset constants exist (defined as static constants in Color)
        • Color.red
        • Color.orange
        • Color.pink
        • etc
    • Examples of different shapes
      • Graphics.drawLine(int x1, int y1, int x2, int y2) draws a straight line from (x1,y1) to (x2,y2)
      • Graphics.drawRect(int x, int y, int w, int h) draws a rectangle from upper left hand corner (x,y) with width w and height h
      • Graphics.drawOval(int x, int y, int w, int h) draws an outline of an ellipse with a ‘bounding rectangle’ as above
      • Graphics.drawPolygon(int[] xc, int[] yc, int n) draws a polygon with n vertices with the co-ordinates being stored in arrays xc and yc
      • Graphics.fillOval (int x, int y, int w, int h) fills the oval with the current draw colour
  • class DrawPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.red); g.drawRect(20,30,50,50); g.setColor(Color.green); g.drawOval(100,30,90,60); g.fillOval(100,30,90,60); g.setColor(Color.yellow); int[] xcoords={180,200,250,275,225}; int[] ycoords={170,130,130,150,200}; g.drawPolygon(xcoords,ycoords,5); g.fillPolygon(xcoords,ycoords,5); } }
  •  
  • Displaying images
    • We can read images stored in GIF and JPEG formats and draw the image onto a graphics panel using Graphics.drawImage()
    • When an image is read from file, a new thread of execution is started in parallel
      • Usually, the program needs to wait until the image is loaded
      • Loaded images need to be ‘tracked’ and the program informed when the loading is complete
  • Normal program thread Load image from file Create new thread Image loading thread Program waits to be informed when image loaded Image loading complete – send signal Normal program thread resumes
    • Image read from file by a Toolkit object
      • getDefaultToolkit() returns the default toolkit
      • getDefaultToolkit().getImage(filename) reads the jpg or gif file containing the image
    • An image is added to a tracker object which sends a signal back to the panel when the loading is complete
    • The try/catch statements are for exception handling – causes the program to wait for the image to be loaded (see later)
    • Following program draws an image into a panel
  • import java.awt.*; import java.awt.event.*; import javax.swing.*; class ImagePanel extends JPanel { public ImagePanel() { image = Toolkit.getDefaultToolkit().getImage( “Pisa.jpg” ); MediaTracker tracker=new MediaTracker(this); tracker.addImage(image,0); try {tracker.waitForID(0);} catch (InterruptedException e){} } public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image,0,0,this); } private Image image; }
  •  
  • And finally ….
    • Swing/AWT are massive and complex
      • We have only scratched the surface
    • Typically Java API’s have been built on top of Swing
      • Java2D
      • Java3D
    • In practice, you would use these to do real work for example involving image processing or 3D rendering
  • “ 640K ought to be enough for anybody.” --Bill Gates, 1981
  • Nu inschrijven voor het schaaktoernooi