This example appears on page 66 of Head First Java.
class Books {
String title;
String author;
}
class BooksTestDrive {
public static void main() {
Books[] myBooks
= new Books[3];
int x = 0;
myBooks[0] = new Books();
myBooks[1] = new Books();
myBooks[2] = new Books();
myBooks[0].title = "The Grapes
of Java";
myBooks[1].title = "The Java
Gatsby";
myBooks[2].title = "The Java
Cookbook";
myBooks[0].author = "bob";
myBooks[1].author = "sue";
myBooks[2].author = "ian";
// The example is
using a while loop where it's actually more convenient to use a for loop
// Think about how you'd change this to be
a for loop
while (x < 3) {
// We have to
convert the print and println's as well
System.out.print(myBooks[x].title);
System.out.print(" by ");
System.out.println(myBooks[x].author);
x = x + 1;
}
}
}
For Processing, this becomes:
class Books {
String title;
String author;
}
Books[] myBooks = new Books[3];
int x = 0;
myBooks[0] = new Books();
myBooks[1] = new Books();
myBooks[2] = new Books();
myBooks[0].title = "The Grapes
of Java";
myBooks[1].title = "The Java
Gatsby";
myBooks[2].title = "The Java
Cookbook";
myBooks[0].author = "bob";
myBooks[1].author = "sue";
myBooks[2].author = "ian";
// The example is using a while loop where
it's actually more convenient to use a for loop
// Think about how you'd change this to be a for loop
while (x < 3) {
print(myBooks[x].title);
print(" by ");
println(myBooks[x].author);
x = x + 1;
}
This example appears on page 67.
class Triangle {
// The class has
class variables (called fields) - this means it's a "real" class (not
a
// dummy entry class)
double area;
int height;
int length;
public static void main(String[] args) {
int x = 0;
Tringle[] ta
= new Triangle[4];
// The example is
using a while loop where it's actually more convenient to use a for loop
// Think about how you'd change this to be
a for loop
while (x < 4 ) {
ta[x] = new Triangle();
ta[x].height = (x + 1) * 2;
ta[x].length = x + 4;
ta[x].setArea();
System.out.print("triangle
"+x+", area");
System.out.println(" = " + ta[x].area);
x = x + 1;
}
int y = x;
x = 27;
Triangle t5 = ta[2];
ta[2].area = 343;
System.out.print("y = " + y);
System.out.println(", t5 rea = " + t5.area);
}
void setArea()
{
area = (height * length) / 2;
}
}
For Processing, this becomes:
class Triangle {
// The class has class
variables (called fields) - this means it's a "real" class (not a
// dummy entry class)
double area;
int height;
int length;
void setArea()
{
area = (height * length) / 2;
}
}
int x = 0;
Triangle[]
ta = new Triangle[4];
// The example is using a while loop where
it's actually more convenient to use a for loop
// Think about how you'd change this to be a for loop
while (x < 4 ) {
ta[x] = new Triangle();
ta[x].height = (x + 1) * 2;
ta[x].length = x + 4;
ta[x].setArea();
print("triangle
"+x+", area");
println(" = " + ta[x].area);
x = x + 1;
}
int y = x;
x =
27;
Triangle
t5 = ta[2];
ta[2].area = 343;
print("y = " + y);
println(", t5 area = " +
t5.area);