我正在用 bluej 编写一个程序,它由几个类组成,这些类获取用户输入并将它们保存为字符串数据。这些类相互覆盖其他方法,并旨在显示在名为 CollegeList 的最终类中。但是,对于 CollegeList 类,我不允许在我的作业中扩展这些子类。相反,我打算使用 bluej '使用关系'并在每个循环中输出这些类的输入和输出。如何才能做到这一点?这是我的一些代码:
// College List
import java.util.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class CollegeList
{
//Input Reader
Scanner scanner = new Scanner(System.in);
private ArrayList<Person> people;
//Main Public Method
public CollegeList()
{
people=new ArrayList<Person>();
}
public void main()//not allowed to extend
{
dataEntry();
}
public void getPeople(Person persons)
{
people.add(persons);
System.out.println(people);;
}
//*** Attempting to output preceding class Person in loop - Must be done this way
public void dataEntry()
{
for(Person persons: people)
{
persons.dataEntry();
}
}
}
Person
班级:
import java.util.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Person extends Student
{
// instance variables for data types
public ArrayList<String> firstName;
public ArrayList<String> lastName;
public ArrayList<String> streetAdress;
public ArrayList<String> postCode;
public ArrayList<String> phoneNumber;
Scanner scanner = new Scanner(System.in);
/**
* Constructor for objects personal details.
*/
public Person()
{
firstName = new ArrayList<String>();
lastName = new ArrayList <String>();
streetAdress = new ArrayList<String>();
postCode = new ArrayList<String>();
phoneNumber = new ArrayList<String>();
}
/**
* Allows User to Enter Details into class Person and Displays it.
*/
public void dataEntry ()
{
System.out.print("Enter First Name: ");
firstName.add(scanner.nextLine());
System.out.print("Enter Last Name: ");
lastName.add(scanner.nextLine());
System.out.print("Enter Street Adress: ");
streetAdress.add(scanner.nextLine());
System.out.print("Enter Post Code: ");
postCode.add(scanner.nextLine());
System.out.print("Enter Phone Number: ");
phoneNumber.add(scanner.nextLine());
//display persons information on single line
System.out.println("The details are - " +
"Name: " +
firstName + "," +
"Surname: " +
lastName + "," +
"Street Adress: " +
streetAdress + "," +
"Post Code: " +
postCode + "," +
"Phone Number: " +
phoneNumber + "." );
}
}