Bond_James_Bond
Bond_James_Bond

Reputation: 41

Store in an ArrayList

How could i store the below code in an array list using Java? Im stuck. Your help will be greatly appreciated.

System.out.println("Please enter Officer's First Name");
firstName = input.next();
officerObject.setOfficerFirstName(firstName);
System.out.println("Enter Officer's Last Name");
lastName = input.next();
officerObject.setOfficerLastName(lastName);
System.out.println("Enter Officer's Badge Number");
badgeNum = input.next();
officerObject.setOfficerBadgeNum(badgeNum);
System.out.println("Enter Officer's Precint");
precint = input.next();
officerObject.setOfficerPrecint(precint);

Upvotes: 0

Views: 57

Answers (2)

Yussef
Yussef

Reputation: 610

Well as he said use a List look

First it could be use like this:

   public static void main(String[] args) {

    Scanner input =  new Scanner(System.in);
    Officer officerObject = new Officer();

    System.out.println("Please enter Officer's First Name");
    officerObject.setOfficerFirstName(input.next());
    System.out.println("Enter Officer's Last Name");
    officerObject.setOfficerLastName(input.next());
    System.out.println("Enter Officer's Badge Number");
    officerObject.setOfficerBadgeNum(input.next());
    System.out.println("Enter Officer's Precint");
    officerObject.setOfficerPrecint(input.next());

    List<Officer> officer = new ArrayList<Officer>();
    officer.add(officerObject);

    for(Officer of: officer){
        System.out.println(of.getOfficerFirstName());
        System.out.println(of.getOfficerLastName());
        System.out.println(of.getOfficerBadgeNum());
        System.out.println(of.getOfficerPrecint());
    }

Upvotes: 0

Naberhausj
Naberhausj

Reputation: 303

Create an array list with List<YOUR OBJECT TYPE> array = new ArrayList<>(); and then use array.add(officerObject); to add it to the array list.

Upvotes: 2

Related Questions