Skip to content

Instantly share code, notes, and snippets.

@rshepherd
Last active August 29, 2015 14:11
Show Gist options
  • Save rshepherd/3b0405beb6b0239f43bc to your computer and use it in GitHub Desktop.
Save rshepherd/3b0405beb6b0239f43bc to your computer and use it in GitHub Desktop.
OOP practice problem
// Let me know if you see any mistakes!!
public class Rectangle {
private int length;
private int width;
public Rectangle() {}
public Rectangle(int width, int length) {
this.setWidth(width);
this.setLength(length);
}
public int getArea() {
return width * length;
}
public int getPerimeter() {
return 2 * width + 2 * length;
}
public boolean isSquare() {
return width == length;
}
public int getLength() {
return length;
}
public void setLength(int length) {
if (length > 0 && length <= 20) {
this.length = length;
} else {
System.out.println("Invalid length. Defaulting to 10.");
this.length = 10;
}
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
if (width > 0 && width <= 20) {
this.width = width;
} else {
System.out.println("Invalid width. Defaulting to 10.");
this.width = 10;
}
}
// There are a number of ways to do this draw function.
// This one is probably not the simplest or the most elegant.
public void draw() {
drawWidth();
drawLength();
drawWidth();
}
private void drawLength() {
for (int j = 0; j < length - 2; ++j) {
for (int i = 0; i < width; ++i) {
if (i == 0 || i == width - 1) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
private void drawWidth() {
for (int i = 0; i < width; ++i) {
System.out.print("*");
}
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment