algoritmiek variables and methods graphics hoorcollege 10 - ma. 6 nov. 2006 l.m. bosveld-de smet
TRANSCRIPT
Variables: kenmerken
Naam Data Type
8 primitive types onbeperkt aantal object of reference types
Bereik (Scope) Levensduur (Lifetime) Initialisatie Declaratie
Variables: verschillende soorten
Local variables
Parameters
Instance variables (non-static fields)
Class variables (static fields)
Variables: overzichtkenmerk local variable /
parameterinstance variable
class variable
plaats van declaratie
vòòr gebruik ergens binnen method , constructor of block; in method-declaratie
ergens binnen class, maar buiten methods;bij voorkeur private
ergens binnen class, maar buiten methods;static en bij voorkeur final
gebruik waarde slechts van belang voor method , constructor of block
waarde van belang voor object’s state en meerdere methods
meestal gebruikt voor constanten
zichtbaarheid onzichtbaar buiten method , constructor of block
zichtbaar voor alle methods in de class; onzichtbaar voor andere classes
zichtbaar voor alle methods in de class; ook zichtbaar buiten de class, als public
levensduur start – exit uitvoer van method , constructor of block
object-aanmaak met new – verdwijnen van referentie naar object
start – exit uitvoer programma
public class variable: voorbeeld
Constante van de Math class (java API)public static final double PI = 3.1415926535…;
public class PrintPI {
public static void main (String[] args){
System.out.println(Math.PI);
}
}
Instance variable: voorbeeld
public class Bicycle {… … …private int speed;… … …public Bicycle (int startSpeed) {
speed = startSpeed;}… … …public int getSpeed (){
return speed;}… … …
}
instance variable
constructor:
Bicycle myBicycle = new Bicycle (10);
getter method:
myBicycle.getSpeed()
public class method: voorbeelden
Methods van de Math class (java API)
public static int round (float a)
public static double sqrt (double a)
public static double random ()
Math.round(5.5)
private class variable / public class method: voorbeelden
public class Bicycle {… … …private int speed;private int id;private static int numberOfBicycles = 0;… … …public Bicycle (int startSpeed) {
speed = startSpeed;id = ++numberOfBicycles;
}… … …public static int getNumberOFBicycles(){
return numberOfBicycles;}… … …
}
class variable
class method:
Bicycle.getNumberOfBicycles
local variables: voorbeeld (1)public class Adding {
public static void main (String[] args) {int next=1;int total = 0;while (next > 0) {
next = Integer.parseInt(SimpleIO.readLine());total = total + next;
}System. out.println("Total is : " + total);
}}
local variables: voorbeeld (2)
while (workToDo (table)) {for (int r = 0; r < table.length; r++) {
for (int c = 0; c < table [0].length; c++) {if (table [r] [c] > 3) {
stamps += 4; table [r] [c] -= 4;
parameter: voorbeeld
public void setFee (double newFee) {
fee = newFee;
}
parameter
doc.setFee (150.00);
Array parameterspublic class WordLists { public static void main(String[] args) String[] wordList1 = {"aap", "hond", "varken", "luipaard",
"bever"}; String[] wordList2 = {"hortensia", "roos", "lelie", "geranium",
"magnolia"}; System.out.println ("Longest word list 1: " +
wordList1[longestWord(wordList1)]); System.out.println ("Longest word list 2: " +
wordList2[longestWord(wordList2)]); }
private static int longestWord(String[] list) { int indexLongestWord = 0; for (int i = 1; i < list.length; i++) { if (list[i].length() > list[indexLongestWord].length()) { indexLongestWord = i; } } return indexLongestWord; }
}
Instance methodspublic class Person {
private String name;
public Person () { name = "no name yet."; }
public Person (String initialName) { name = initialName; }
public void setName (String newName) { name = newName; }
public String getName () { return name; }
public void writeOutput () { System.out.println ("Name: " + name); }
public boolean sameName (Person otherPerson) { return (this.name.equalsIgnoreCase (otherPerson.name)) }
}
Class methods: examples
public static void callByName (String name) { system.out.print (name);}
private static int updateScore (int currentScore, int points) {
return currentScore + points;}
Class var./method: gebruik in class
public class <class_name>
<declaratie class variable(s)>
public static void main (String [] args) {
<main body>
}
<declaratie class method(s)>
}
Verdeling van taken
Quiz-programma:
Stel een vraag aan de gebruiker Lees het antwoord van de gebruiker Controleer of het antwoord correct is Geef adequate feedback Hou de score bij
Class “helper” methods private static String readAnswer (String question) { SimpleIO.prompt (question); String userInput = SimpleIO.readLine(); return userInput.trim().toLowerCase(); }
private static boolean match (String userAnswer, String correctAnswer) { return (userAnswer.equals(correctAnswer)); }
private static void giveFeedback (boolean ok, String hurrah, String sorry) {
System.out.println (ok ? hurrah : sorry); }
private static void updateScore (boolean ok) { if (ok) { score += 10; } }
Gebruik van “helpers” in mainimport jpb.*;public class Quiz { private static int score; public static void main(String[] args) { score = 0; String userAnswer = ""; boolean isCorrect = false; userAnswer = readAnswer ("Waarvan is bit de afkorting?\n") ; isCorrect = match (userAnswer, "binary digit") ; giveFeedback (isCorrect, "Goed geantwoord!", "Sorry. Verkeerd
antwoord."); updateScore (isCorrect) ; userAnswer = readAnswer ("Hoeveel bytes komen overeen met 32
bits?\n") ; isCorrect = match (userAnswer, "4") ; giveFeedback (isCorrect, "Het gaat prima zo!", "Wat jammer nu!") ; updateScore (isCorrect) ; System.out.println ("Your total score is " + score + " points."); } <declaration helpers>}
DrawableFrame object en methoden
import java.awt.*;import jpb.*;
public class <class name> {public static void main (String[] args) {
// create drawable frameDrawableFrame df = new DrawableFrame(<frame title>);df.show() / df.setVisible(true);df.setSize(<width>,<height>);
// obtain graphics contextGraphics g = df.getGraphicsContext();
//make drawing<Graphics methods applied to Graphics object>;
// repaint framedf.repaint();
}}
DrawLine class// draws a line inside a frame
import java.awt.*;import jpb.*;
public class DrawLine {public static void main (String[] args) {
// create drawable frameDrawableFrame df = new DrawableFrame("Line");df.setVisible(true);df.setSize(200,200);
// obtain graphics contextGraphics g = df.getGraphicsContext();
// draw lineg.drawLine(50,50,150,150);
// repaint framedf.repaint();
}}
Gele achtergrondvorm stoplicht
// Draw background of sign
g.setColor(Color.yellow)
int[] xBackground = {0, 100, 200, 100};
int[] yBackground = {100, 0, 100, 200}; g.fillPolygon(xBackground, yBackground,
xBackground.length);
X coordinaten van vorm
Y coordinaten van vorm
kleur van de vorm
5 geneste vierkanten// Draw five nested polygons to form the stripe on the// outer border of the sign
g.setColor(Color.black); int[] xPolygon1 = {5, 100, 195, 100}; int[] yPolygon1 = {100, 5, 100, 195}; g.drawPolygon(xPolygon1, yPolygon1, xPolygon1.length); int[] xPolygon2 = {6, 100, 194, 100}; int[] yPolygon2 = {100, 6, 100, 194}; g.drawPolygon(xPolygon2, yPolygon2, xPolygon2.length); int[] xPolygon3 = {7, 100, 193, 100}; int[] yPolygon3 = {100, 7, 100, 193}; g.drawPolygon(xPolygon3, yPolygon3, xPolygon3.length); int[] xPolygon4 = {8, 100, 192, 100}; int[] yPolygon4 = {100, 8, 100, 192}; g.drawPolygon(xPolygon4, yPolygon4, xPolygon4.length); int[] xPolygon5 = {9, 100, 191, 100}; int[] yPolygon5 = {100, 9, 100, 191}; g.drawPolygon(xPolygon5, yPolygon5, xPolygon5.length);
Tekenen van stoplicht
// Draw a black rectangle (the traffic signal)
g.fillRect(77, 35, 46, 130);
// Draw red,yellow,and green circles (the traffic
// lights)
g.setColor(Color.red);
g.fillOval(83, 43, 34, 34);
g.setColor(Color.yellow);
g.fillOval(83, 84, 34, 34);
g.setColor(Color.green);
g.fillOval(83, 125, 34, 34);
Toon tekst: programmaimport java.awt.*;import jpb.*;
public class DisplaySum {public static void main (String[] args) {
// create drawable frameDrawableFrame df = new DrawableFrame("Wirth's RULE");df.setVisible(true);df.setSize(350,200);
// obtain graphics contextGraphics g = df.getGraphicsContext();
// display text in red monospaced bold fontg.setColor(Color.red);g.setFont(new Font("Monospaced", Font.BOLD, 30));g.drawString("DATA STRUCTURES + ", 15, 50);
// display text in green sansserif italic font fontg.setColor(Color.green);g.setFont(new Font("SansSerif", Font.ITALIC, 30));g.drawString("ALGORITHMS = ", 15, 100);
// display text in blueserif plain fontg.setColor(Color.blue);g.setFont(new Font("Serif", Font.PLAIN, 40));g.drawString("PROGRAMS", 15, 150);
// repaint framedf.repaint();
}}