0% found this document useful (0 votes)
33 views8 pages

A Programming Problem: Algoritmalar Ve Programlama II

Uploaded by

Nora Masoud
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views8 pages

A Programming Problem: Algoritmalar Ve Programlama II

Uploaded by

Nora Masoud
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

3/6/2023

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

• Write a program to draw the cities on a DrawingPanel, then drop a


"bomb" that turns all cities red that are within a given radius:
Blast site x? 100
Blast site y? 100
Blast radius? 75
Kaboom! 4

1 4

Güz 2022 – Alg. ve Prog. I A bad solution


• Primitive Data Types Scanner input = new Scanner(new File("cities.txt"));
int cityCount = input.nextInt();
• Definite Loops int[] xCoords = new int[cityCount];
int[] yCoords = new int[cityCount];
• Conditional Executions
for (int i = 0; i < cityCount; i++) {
• Programming Logic and Indefinite Loops xCoords[i] = input.nextInt(); // read each city
yCoords[i] = input.nextInt();
• Parameters and Objects }
...
• Arrays

– parallel arrays: 2+ arrays with related data at same indexes.


• Considered poor style.

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.

Chapter 8 – We could compare distances between Points


to see whether the bomb hit a given city.

Classes
– Each Point would know how to draw itself.

Copyright (c) Pearson 2020.


– The overall program would be shorter and cleaner.
All rights reserved.

3 6

1
3/6/2023

Clients of objects Abstraction


• client program: A program that uses objects. • abstraction: A distancing between ideas and details.
– Example: Bomb is a client of DrawingPanel and Graphics. – We can use objects without knowing how they work.

Bomb.java (client program)


DrawingPanel.java (class) • abstraction in an iPod:
public class DrawingPanel {
public class Bomb {
... – You understand its external behavior (buttons, screen).
main(String[] args) {
new DrawingPanel(...)
} – You don't understand its inner details, and you don't need to.
new DrawingPanel(...)
...
}
}

7 10

7 10

Classes and objects Our task


• class: A program entity that represents either: • In the following slides, we will implement a Point class as a
1. A program / module, or way of learning about defining classes.
2. A template for a new type of objects.
– We will define a type of objects named Point.
– The DrawingPanel class is a template for creating – Each Point object will contain x/y data called fields.
DrawingPanel objects. – Each Point object will contain behavior called methods.
– Client programs will use the Point objects.

• object: An entity that combines state and behavior.


– object-oriented programming (OOP): Programs that perform
their behavior as interactions between objects.

8 11

8 11

Blueprint analogy Point objects (desired)


iPod blueprint Point p1 = new Point(5, -2);
state: Point p2 = new Point(); // origin, (0, 0)
current song
volume
battery life • Data in each Point object:
behavior:
power on/off Field name Description
change station/song
change volume x the point's x-coordinate
choose random song
y the point's y-coordinate
creates

iPod #1 iPod #2 iPod #3 • Methods in each Point object:


state: state: state: Method name Description
song = "1,000,000 Miles" song = "Letting You" song = "Discipline"
volume = 17 volume = 9 volume = 24
battery life = 2.5 hrs battery life = 3.41 hrs battery life = 1.8 hrs setLocation(x, y) sets the point's x and y to the given values
behavior: behavior: behavior: translate(dx, dy)
power on/off power on/off power on/off adjusts the point's x and y by the given amounts
change station/song change station/song change station/song
change volume change volume change volume distance(p) how far away the point is from point p
choose random song choose random song choose random song
draw(g) displays the point on a drawing panel
9 12

9 12

2
3/6/2023

Point class as blueprint Fields


state:
Point class
• field: A variable inside an object that is part of its state.
int x, y – Each object has its own copy of each field.
behavior:
setLocation(int x, int y)
translate(int dx, int dy)
distance(Point p)
draw(Graphics g)
• Declaration syntax:
type name;
Point object #1 Point object #2 Point object #3
state:
x = 5, y = -2
state:
x = -245, y = 1897
state:
x = 18, y = 42 – Example:
behavior: behavior: behavior:
setLocation(int x, int y) setLocation(int x, int y) setLocation(int x, int y) public class Student {
translate(int dx, int dy) translate(int dx, int dy) translate(int dx, int dy)
distance(Point p) distance(Point p) distance(Point p) String name; // each Student object has a
draw(Graphics g) draw(Graphics g) draw(Graphics g)
double gpa; // name and gpa field
}
– The class (blueprint) will describe how to create objects.
– Each object will contain its own data and methods.
13 16

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

Point class, version 1 A class and its client


public class Point { • Point.java is not, by itself, a runnable program.
int x;
– A class can be used by client programs.
int y;
} Point.java (class of objects)
PointMain.java (client program) public class Point {
– Save this code into a file named Point.java. public class PointMain { int x;
main(String args) { int y;
Point p1 = new Point(); }
• The above code creates a new type named Point. p1.x = 7;
p1.y = 2;
– Each Point object contains two pieces of data:
Point p2 = new Point(); x 7 y 2
• an int named x, and p2.x = 4;
• an int named y. p2.y = 3;
...
} x 4 y 3
}
– Point objects do not contain any behavior (yet).

15 18

15 18

3
3/6/2023

PointMain client example Null pointer exception


public class PointMain {
public static void main(String[] args) {
• dereference: To access data or methods of an object with the
// create two Point objects dot notation, such as s.length() .
Point p1 = new Point(); – It is illegal to dereference null (causes an exception).
p1.y = 2;
Point p2 = new Point(); – null is not any object, so it has no methods or data.
p2.x = 4;
System.out.println(p1.x + ", " + p1.y); // 0, 2 String[] words = new String[5];
System.out.println("word is: " + words[0]);
// move p2 and then print it
p2.x += 2; words[0] = words[0].toUpperCase(); // ERROR
p2.y++;
System.out.println(p2.x + ", " + p2.y); // 6, 1 index 0 1 2 3 4
} Output: value null null null null null
}
word is: null
Exception in thread "main"
• Exercise: Modify the Bomb program to use Point objects. java.lang.NullPointerException
at Example.main(Example.java:8)
19 22

19 22

Arrays of objects Looking before you leap


• null : A value that does not refer to any object. • You can check for null before calling an object's methods.
– The elements of an array of objects are initialized to null. String[] words = new String[5];
words[0] = "hello";
String[] words = new String[5]; words[2] = "goodbye"; // words[1], [3], [4] are null
DrawingPanel[] windows = new DrawingPanel[3];
for (int i = 0; i < words.length; i++) {
if (words[i] != null) {
index 0 1 2 3 4 words[i] = words[i].toUpperCase();
words value null null null null null
}
}

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

Things you can do w/ null Two-phase initialization


• store null in a variable or an array element 1) initialize the array itself (each element is initially null)
String s = null; 2) initialize each element of the array to be a new object
words[2] = null;
String[] words = new String[4]; // phase 1
• print a null reference for (int i = 0; i < words.length; i++) {
System.out.println(s); // null coords[i] = "word" + i; // phase 2
}
• ask whether a variable or array element is null
if (words[2] == null) { ... index 0 1 2 3
words
• pass null as a parameter to a method value "word0" "word1" "word2" "word3"
System.out.println(null); // null

• return null from a method (often to indicate failure)


return null;
21 24

21 24

4
3/6/2023

Bomb answer 1 Client code redundancy


import java.awt.*;
import java.io.*; • Our client program wants to draw Point objects:
import java.util.*;
// Displays a set of cities and simulates dropping a "bomb" on them.
// draw each city
public class Bomb { g.fillOval(cities[i].x, cities[i].y, 3, 3);
public static void main(String[] args) throws FileNotFoundException { g.drawString("(" + cities[i].x + ", " + cities[i].y + ")",
DrawingPanel panel = new DrawingPanel(200, 200);
Graphics g = panel.getGraphics(); cities[i].x, cities[i].y);

Scanner input = new Scanner(new File("cities.txt"));


Point[] cities = readCities(input, g);

// drop the "bomb"


• To draw them in other places, the code must be repeated.
Scanner console = new Scanner(System.in);
Point bomb = new Point(); – We can remove this redundancy using a method.
System.out.print("Blast site x? ");
bomb.x = console.nextInt();
System.out.print("Blast site y? ");
bomb.y = console.nextInt();
System.out.print("Blast radius? ");
int radius = console.nextInt();
boom(bomb, radius, cities, g);
}
...

25 28

25 28

Bomb answer 2 Eliminating redundancy, v1


// Reads input file of cities and returns them as array of Points.
public static Point[] readCities(Scanner input, Graphics g) { • We can eliminate the redundancy with a static method:
int numCities = input.nextInt(); // first line = # of cities
Point[] cities = new Point[numCities]; // Draws the given point on the DrawingPanel.
for (int i = 0; i < cities.length; i++) {
cities[i] = new Point(); public static void draw(Point p, Graphics g) {
cities[i].x = input.nextInt(); // read city x/y from file
cities[i].y = input.nextInt(); g.fillOval(p.x, p.y, 3, 3);
g.fillOval(cities[i].x, cities[i].y, 3, 3);
g.drawString("(" + cities[i].x + ", " + cities[i].y + ")",
g.drawString("(" + p.x + ", " + p.y + ")", p.x, p.y);
cities[i].x, cities[i].y); }
}
return cities;
}
// Simulates dropping a bomb at the given location on the given cities.
public static void boom(Point bomb, int radius, Point[] cities, Graphics g) {
g.setColor(Color.RED);
• main would call the method as follows:
g.drawOval(bomb.x - radius, bomb.y - radius, 2 * radius, 2 * radius);
for (int i = 0; i < cities.length; i++) { // draw each city
int dx = cities[i].x - bomb.x;
int dy = cities[i].y - bomb.y; draw(cities[i], g);
double distance = Math.sqrt(dx * dx + dy * dy);
if (distance <= radius) {
g.fillOval(cities[i].x, cities[i].y, 3, 3);
g.drawString("(" + cities[i].x + ", " + cities[i].y + ")",
cities[i].x, cities[i].y);
}
}
System.out.println("Kaboom!");
}
}

26 29

26 29

Problem with static method


• We are missing a major benefit of objects: code reuse.
– Every program that draws Points would need a draw method.

Object behavior: Methods • The syntax doesn't match how we're used to using objects.
draw(cities[i], g); // static (bad)

• The point of classes is to combine state and behavior.


– The draw behavior is closely related to a Point's data.
– The method belongs inside each Point object.

cities[i].draw(g); // inside object (better)


30

27 30

5
3/6/2023

Instance methods The implicit parameter


• instance method (or object method): Exists inside each • implicit parameter:
object of a class and gives behavior to each object. The object on which an instance method is called.

public type name(parameters) { – During the call p1.draw(g);


statements; the object referred to by p1 is the implicit parameter.
}
– During the call p2.draw(g);
– same syntax as static methods, but without static keyword the object referred to by p2 is the implicit parameter.

– The instance method can refer to that object's fields.


Example:
• We say that it executes in the context of a particular object.
public void shout() {
•draw can refer to the x and y of the object it was called on.
System.out.println("HELLO THERE!");
}
31 34

31 34

Instance method example Point class, version 2


public class Point { public class Point {
int x; int x;
int y; int y;
// Changes the location of this Point object.
// Draws this Point object with the given pen.
public void draw(Graphics g) {
public void draw(Graphics g) { g.fillOval(x, y, 3, 3);
... g.drawString("(" + x + ", " + y + ")", x, y);
} }
} }

– 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

Point objects w/ method Kinds of methods


• Each Point object has its own copy of the draw method, which • accessor: A method that lets clients examine object state.
operates on that object's state: – Examples: distance, distanceFromOrigin
p1
– often has a non-void return type
Point p1 = new Point();
p1.x = 7;
p1.y = 2;
x 7 y 2
Point p2 = new Point();
• mutator: A method that modifies an object's state.
public void draw(Graphics g) {
p2.x = 4; // this code can see p1's x and y – Examples: setLocation, translate
p2.y = 3; }

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

Mutator method questions Accessor method answers


• Write a method setLocation that changes a Point's public double distance(Point other) {
int dx = x - other.x;
location to the (x, y) values passed. int dy = y - other.y;
return Math.sqrt(dx * dx + dy * dy);
}
• Write a method translate that changes a Point's location
by a given dx, dy amount. public double distanceFromOrigin() {
return Math.sqrt(x * x + y * y);
}
– Modify the Point and client code to use these methods.
// alternative solution that uses distance
public double distanceFromOrigin() {
Point origin = new Point();
return distance(origin);
}

37 40

37 40

Mutator method answers Printing objects


public void setLocation(int newX, int newY) { • By default, Java doesn't know how to print objects:
x = newX;
y = newY; Point p = new Point();
} p.x = 10;
p.y = 7;
System.out.println("p is " + p); // p is Point@9e8c34
public void translate(int dx, int dy) {
x = x + dx;
y = y + dy;
// better, but cumbersome; p is (10, 7)
}
System.out.println("p is (" + p.x + ", " + p.y + ")");
// alternative solution that utilizes setLocation
public void translate(int dx, int dy) {
setLocation(x + dx, y + dy); // desired behavior
} System.out.println("p is " + p); // p is (10, 7)

38 41

38 41

Accessor method questions The toString method


• Write a method distance that computes the distance tells Java how to convert an object into a String
between a Point and another Point parameter.
Point p1 = new Point(7, 2);
Use the formula: (x2 − x1 )2 + ( y2 − y1 )2 System.out.println("p1: " + p1);

// the above code is really calling the following:


• Write a method distanceFromOrigin that returns the System.out.println("p1: " + p1.toString());
distance between a Point and the origin, (0, 0).

• Every class has a toString, even if it isn't in your code.


– Modify the client code to use these methods.
– Default: class's name @ object's memory address (base 16)

Point@9e8c34

39 42

39 42

7
3/6/2023

toString syntax
public String toString() {
code that returns a String representing this object;
}

– Method name, return, and parameters must match exactly.

– Example:
// Returns a String representing this Point.
public String toString() {
return "(" + x + ", " + y + ")";
}

43

43

You might also like