0

So I have a list of a class type. For example, I have a ClassRoom class and a Student class.

I created an ArrayList of Students: ArrayList<Student> studList = new ArrayList<>();

I have a method to add a student, so index 0 is occupied:

    public void addStudent(int studID, String studName, int studPhoneNum){
        Student stud = new Student(studName, studID, studPhoneNum);
        studList.add(stud);
        System.out.println(studList);
    }

Now what I want is to search for a specific value inside the student's variables. So for example, a student is represented by a name, ID and phone number. How do I loop over that Student list to find a student with a specific phone number, then print him or his phone number?

This is the function:

    public void sendMessage(int phone){
        for (Student s : studList) {
            studList.get(studPhoneNum);
            \\ then print the Student the phone number belongs to..
        }
    }

I do have a studPhoneNum variable set in the Student class.

2
  • 4
    if(s.getPhonenumber == phone) Commented Jan 13, 2020 at 9:22
  • Thank you! I can't believe I didn't find this earlier. Commented Jan 13, 2020 at 9:30

3 Answers 3

1

The easiest way would be to create a function to get the phone number like this:

public int getPhoneNumber(int stuID){
    for (Student s: studList) {
        if(s.id == stuID){
            return s.phoneNumber;
        }
    }
    return 0;
}

I'm supposing here that stuList is a global variable since you can access to it in addStudent without passing it as an argument, otherwise you'll have to pass it to the function. I hope it helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I was missing the whole s.something thing. This works perfectly :)
1

You can do as below:

  1. Using Java 8 stream:

    studList.stream()
            .filter(student -> student.getStudPhoneNum==studPhone)
            .findFirst()
            .ifPresent(student -> {
                // Do something
            });
    
  2. Using for loop:

    for(Student s: studList){
        if(s.getStudPhoneNum==studPhone){
            //do something
        }
    }
    

Comments

1

Since you are iterating over studList, 's' represents every individual student in that list.

public void sendMessage(int phone){
    for (Student s : studList) {
        if (s.getStudPhoneNum() == phone){
             System.out.print(s.getStudName());
        }
    }
}

Here you would need to create getter methods (getStudPhoneNumber(), getStudName())to refer attributes of the Student class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.