我提出了一個問題來創建一個“person”類,一個繼承“person”的“staff”類,一個可以包含 Person 陣列(3)的“room”類,然后創建所有 setter 和 getter 以及一個方法呼叫 show() 列印屬性,呼叫主類創建“房間”,添加 2 個“人”和 1 個“員工”,然后列印所有屬性。
我完成了“人”和“員工”課程。
class Person{
protected String Name;
protected int Age;
//... i had done the person class including the getter and setter
繼承了 person 類并顯示輸出的人員類
class Staff extends Person{
private double Salary;
...
@Override
public void show(){
System.out.println("Name: " this.Name);
System.out.println("Age: " this.Age);
System.out.println("Salary: RM " df.format(this.Salary));
}
我不確定如何在 Room 類中創建一個陣列以及如何在主類中訪問它。在主要課程中,我應該是(a)創建一個房間。(b) 添加一個以您的名字命名的人。(c) 添加帶有您父親姓名的作業人員。(d) 添加一個有你母親名字的人。(e) 將所有人員詳細資訊列印到控制臺。
我曾嘗試創建一個陣列并列印出所有屬性,它運行良好,但問題要求我創建房間類,所以我對如何做有點困惑。
class Main{
public static void main(String[] args) {
Person family[] = new Person[3];
family[0] = new Person("Me", 20);
family[1] = new Staff("Papa", 60, 300);
family[2] = new Person("Mama", 55);
for(int i = 0; i<family.length; i ) {
family[i].show();
System.out.println(" ");
}
}
}
請幫我安排房間和主要課程。
uj5u.com熱心網友回復:
像這樣的東西?
房間.java:
class Room {
private Person[] persons;
public Room(Person[] persons){
this.persons = persons;
}
public void listAllPersons() {
// loop over array and print details
}
// add getters and setters as you need
}
主類:
public static void main (String[] args) {
Person persons[] = new Person[3];
persons[0] = new Person("Me", 20);
persons[1] = new Staff("Papa", 60, 300);
persons[2] = new Person("Mama", 55);
Room room = new Room(persons);
room.listAllPersons();
}
uj5u.com熱心網友回復:
Class Room可以這樣實作:
public class Room {
private final int capacity;
private Person[] persons;
private int id;
public Room(int capacity) {
this.capacity = capacity;
this.persons = new Person[capacity];
}
/**
* return true if capacity of the room is not
* exceeded and new person was added successfully
*/
public boolean addPerson(Person pers) {
if (id == capacity) {
return false;
}
persons[id ] = pers;
return true;
}
public void showPersons() {
/*
if you are familiar with streams you can use it instead of a loop,
otherwise remove commented limes
Arrays.stream(persons).forEach(Person::show);
*/
for (var pers: persons)
pers.show();
}
public Person[] getPersons() {
return persons;
}
}
主類- 您的客戶:
public class Main {
public static void main(String[] args) {
Room room = new Room(3);
room.addPerson(new Person(new Person("Me", 20)));
room.addPerson(new Person(new Staff("Papa", 60, 300)));
room.addPerson(new Person(new Person("Mama", 55)));
room.showPersons();
}
}
如果還有什么不清楚的地方,請隨時提問。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/414097.html
標籤:
