|
我没达到要求吗?要怎么改?
Define a class called Animal with the following data attributes:
Desc:array of 20 characters
Height: float
Weight: Float
Define a class Bird that inherits from Animal class above with the following attributes:
Wingspan:float
You program should be able to store up to 10 BirdRec records in an array called BirdsArray.
Your program should at least perform the below operations:
-Add new bird records into BirdsArray
-Display all Birds' records
-Display the bird details with the largest winspan
-Display the bird details with the smallest winspan
Requirement:
Your program should apply the concepts of class, array of objects and inheritance.
答案:
class Animal {
public char[] Desc = new char[20];
public float Height;
public float Weight;
public Animal() {
this(new char[1], 0.0f, 0.0f);
}
public Animal(char[] desc, float height, float weight) {
this.Desc = desc;
this.Height = height;
this.Weight = weight;
}
}
class Bird extends Animal {
public float wingspan;
public Bird() {
this(0.0f, new char[1], 0.0f, 0.0f);
}
public Bird(float ws) {
this(ws, new char[1], 0.0f, 0.0f);
}
public Bird(float ws, char[] desc, float height, float weight) {
super(desc, height, weight);
wingspan = ws;
}
}
public class QBird {
public Bird[] birds;
public int pointer;
public QBird() {
birds = new Bird[10];
pointer = 0;
}
public synchronized boolean addBird(Bird newBird) {
if (pointer >= birds.length) return false;
birds[pointer++] = newBird;
return true;
}
public void displayBird(Bird b) {
System.out.print("\nBird description: ");
System.out.print(b.Desc);
System.out.println("\nBird Height: " + b.Height + "\nBird Weight: " + b.Weight +
"\nBird wingspan: " + b.wingspan);
}
public void displayLargestWingspan() {
int p = 0;
for (int i = 1; i < birds.length && i < pointer; ++i) if (birds.wingspan > birds[p].wingspan) p = i;
System.out.println("Largest Wingspan - " + birds[p].wingspan + ":");
displayBird(birds[p]);
}
public void displaySmallestWingspan() {
int p = 0;
for (int i = 1; i < birds.length && i < pointer; ++i) if (birds.wingspan < birds[p].wingspan) p = i;
System.out.println("Smallest Wingspan - " + birds[p].wingspan + ":");
displayBird(birds[p]);
}
public void displayBirds() {
for (int i = 0; i <birds.length && i < pointer; ++i) displayBird(birds);
}
public static void main(String[] args) {
QBird p = new QBird();
p.addBird(new Bird(5, "Duck".toCharArray(), 10.0f, 20.0f));
p.addBird(new Bird(10, "Swan".toCharArray(),20.0f, 30.0f));
p.addBird(new Bird(80, "Phenix".toCharArray(), 70.0f, 90.0f));
p.addBird(new Bird(200, "Peacock".toCharArray(), 30.0f, 40.0f));
p.displayBirds();
p.displayLargestWingspan();
p.displaySmallestWingspan();
}
} |
|