A Programming Problem: Algoritmalar Ve Programlama II
A Programming Problem: Algoritmalar Ve Programlama II
A programming problem
• Given a file of cities' (x, y) coordinates,
which begins with the number of cities:
BSM 104
6
50 20
90 60
Algoritmalar ve Programlama II 10 72
74 98
5 136
150 91
Bahar 2023
1 4
2 5
2 5
Observations
• The data in this problem is a set of points.
• It would be better stored as Point objects.
Building Java Programs – A Point would store a city's x/y data.
Classes
– Each Point would know how to draw itself.
3 6
1
3/6/2023
7 10
7 10
8 11
8 11
9 12
2
3/6/2023
13 16
Accessing fields
• Other classes can access/modify an object's fields.
– access: variable.field
– modify: variable.field = value;
Object state: Fields
• Example:
Point p1 = new Point();
Point p2 = new Point();
System.out.println("the x-coord is " + p1.x); // access
p2.y = 13; // modify
17
14 17
15 18
15 18
3
3/6/2023
19 22
index 0 1 2
index 0 1 2 3 4
windows
value null null null words
value "HELLO" null "GOODBYE" null null
20 23
20 23
21 24
4
3/6/2023
25 28
25 28
26 29
26 29
Object behavior: Methods • The syntax doesn't match how we're used to using objects.
draw(cities[i], g); // static (bad)
27 30
5
3/6/2023
31 34
– The draw method no longer has a Point p parameter. – Each Point object contains a draw method that draws that point
– How will the method know which point to draw? at its current x/y position.
• How will the method access that point's x/y data?
32 35
32 35
p1.draw(g);
x 4 y 3
p2.draw(g); p2 public void draw(Graphics g) {
// this code can see p2's x and y
}
33 36
33 36
6
3/6/2023
37 40
37 40
38 41
38 41
Point@9e8c34
39 42
39 42
7
3/6/2023
toString syntax
public String toString() {
code that returns a String representing this object;
}
– Example:
// Returns a String representing this Point.
public String toString() {
return "(" + x + ", " + y + ")";
}
43
43