John P.
John P.

Reputation: 215

How to get the name of an object to call a class method if I don't know the name?

I have a class called AttendanceSystem:

LinkedList<LinkedList<String>> student = new LinkedList<LinkedList<String>>();

public AttendanceSystem(String s){
    student.add(new LinkedList<String>());
    student.get(student.size()-1).add(s);
}

public void setEmail(String d){
     student.get(student.size()-1).add(d);
}

In my main I have this:

System.out.println("Please enter your ID.");
String s = keyboard.nextLine();      
new AttendanceSystem(s);

System.out.println("Please enter your Email.");
String d = keyboard.nextLine();  

I want to add more elements into the object but since I used new AttendanceSystem(s) I don't know the name of the object I created so I cannot simply do objectname.setEmail(s). How can I call a method to that very object? Or is there a better way to do this?

I am using a scanner so I can keep adding new objects automatically until I tell it to stop.

UPDATED:

My main now:

  LinkedList<AttendanceSystem> list = new LinkedList<AttendanceSystem>();

System.out.println("Please enter your ID.");
String s = keyboard.nextLine();      
list.add(new AttendanceSystem(s));

System.out.println("Please enter your Email.");
String d = keyboard.nextLine();    
list.get(list.size()-1).setEmail(d);

I stored all the objects in a linked list so I can just do this list.get(list.size()-1).setEmail(d);.

Upvotes: 1

Views: 62

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56433

Simply:

AttendanceSystem identiferName = new AttendanceSystem(s);

then use the setEmail to set the relevant data for that object.

EDIT

you might want to create an addAttendee method which will take the ID and Email then simply add it to the LinkedList inside the AttendanceSystem class.

public void addAttendee(String id, String email){
       LinkedList<String> myList = new LinkedList<>();
       myList.add(id);
       myList.add(email);
       this.student.add(myList);
}

note - in this case, you should just get rid of the constructor parameter & don't use it to add any IDs or Emails.

With does changes in mind and considering that you don't want to store a reference to a new object, you call it like this:

new AttendanceSystem().addAttendee(id,email);

Upvotes: 2

Related Questions