For this assignment you will write a Java class that manages an array list of SimpleStudent objects. The SimpleStudent class is supplied; make no changes to this class.
Begin by downloading the ArrayListSimpleStudent zip file and extracting the SimpleStudent class. After examining this class, add to the project a program containing main() that manages an array list of SimpleStudent objects. Your program will:
- Ask the user the number of students to store.
- Set up an array list to hold this number of SimpleStudent objects.
- Allow the user to enter student information and store the associated SimpleStudent objects in the array list.
- After the students have been entered into the list, display the contents of the list:
- This helps the programmer in debugging the code.
- Ask the user for a student to search for in the list.
- Search the list to determine if this student is in the list:
- If so, state this and give the index of the first occurrence of the student in the list.
- If you find the student, you do not need to search further; there is no requirement to determine how many times the student appears in the list.
- If not, state this.
- If so, state this and give the index of the first occurrence of the student in the list.
Notes/Hints:
- One way to simplify main() is to write a method in the file with main() that allows the user to enter a student’s data, sets up a SimpleStudent object and returns this object to main().
- A good name for this method would be enterSimpleStudent().
- If you write a method of this type, be sure to set up a Scanner object in the method for use within the method. Don’t try to share the Scanner object in main() with another method; this leads to many problems.
A run of the program might look like the following:
Number of students: 4
Enter student information:
Student #1:
Name: Frank
Age: 21
Student #2:
Name: John
Age: 23
Student #3:
Name: Sally
Age: 21
Student #4:
Name: Bill
Age: 23
Students: [[Frank; 21], [John; 23], [Sally; 21], [Bill; 23]]
Enter student to search for in list:
Name: Sally
Age: 21
[Sally; 21] is in the list at index 2.
// SimpleStudent.java
// Class to hold student's last name and age.
public class SimpleStudent
{
// Constructor.
public SimpleStudent(String last, int years)
{
lastName = last;
age = years;
}
// SimpleStudent's get() methods.
public String getLastName()
{
return lastName;
}
public int getAge()
{
return age;
}
// SimpleStudent's set() methods.
public void setLastName(String last)
{
lastName = last;
}
public void setAge(int years)
{
age = years;
}
// SimpleStudent's toString() method.
public String toString()
{
String stdt = "";
stdt = "[" + lastName + "; " + age + "]";
return stdt;
}
// SimpleStudent's equals() method.
// Compares both name and age.
public boolean equals(Object obj)
{
SimpleStudent s2 = (SimpleStudent)obj;
boolean flag = (lastName.equals(s2.lastName)) &&
(age == s2.age);
return flag;
}
// Instance variables.
private String lastName;
private int age;
}