166 Review QuestionsΒΆ
Write a function called getColor(name)
that takes the English name of a
color as input, and returns an RGB triple for that color. Make it work for, at
least, red, green, blue, white, and black.
You could use it to write code like this:
color sky = getColor("blue");
color apple = getColor("red");
color snow = getColor("white");
Solution:
color getColor(String name) {
if (name.equals("red")) {
return color(255, 0, 0);
} else if (name.equals("green")) {
return color(0, 255, 0);
} else if (name.equals("blue")) {
return color(0, 0, 255)
} else if (name.equals("white")) {
return color(255)
} else if (name.equals("black")) {
return color(0);
} else {
println("Unknown color:\"" + name + "\"");
return color(0);
}
}
Write a program that draws a green-filled circle in the center of the screen. When the mouse hovers over the circle, it changes to red-filled. When the mouse moves off the circle, it changes back to green.
Solution:
void setup() {
size(500, 500);
smooth();
noStroke();
}
void draw() {
background(255);
if (dist(mouseX, mouseY, 250, 250) <= 100) {
fill(255, 0, 0);
} else {
fill(0, 255, 0);
}
ellipse(250, 250, 200, 200);
}
Write a program that prints the numbers from 100 down to 1 on the screen, and then prints “Blast off!”:
100
99
98
...
3
2
1
Blast off!!
Do this first using a while-loop, and then using a for-loop.
Solution:
//
// while loop
//
void setup() {
int i = 100;
while (i > 0) {
println(i);
i += -1;
}
println("Blast off!");
}
//
// for-loop 1
//
void setup() {
for(int i = 100; i > 0; --i) {
println(i);
}
println("Blast off!");
}
//
// for-loop 2
//
void setup() {
for(int i = 0; i < 100; ++i) {
println(100 - i);
}
println("Blast off!");
}
Write a class called Point
that represents a 2-dimensional (x, y) point.
It should work with code like this:
Point a = new Point(200, 300);
Point b = new Point(a);
Point origin = new Point();
a.display(); // prints "(200.0, 300.0)" on the console
b.display(); // prints "(200.0, 300.0)" on the console
origin.display(); // prints "(0.0, 0.0)" on the console
Solution:
class Point {
float x, y;
Point() { // default constructor
x = 0;
y = 0;
}
Point(float initX, float initY) {
x = initX;
y = initY;
}
Point(Point other) { // copy constuctor
x = other.x;
y = other.y;
}
void display() {
println("(" + x + ", " + y + ")");
}
}
void setup() {
Point a = new Point(200, 300);
Point b = new Point(a);
Point origin = new Point();
a.display(); // prints "(200, 300)"
b.display(); // prints "(200, 300)"
origin.display(); // prints "(0, 0)"
}