Create a class named Student that includes String data fields titled firstName a
ID: 3539977 • Letter: C
Question
Create a class named Student that includes String data fields titled firstName and lastName, and an integer field titled studentID. Create a constructor that requires two String parameters and one integer parameter to populate the firstName, lastName, and studentID fields. Create a LinkedList of 20 Student objects each having different first names, last names, and student IDs. Print your LinkedList, first in the order your items were placed onto the LinkedList and then in reverse order. Save your files as Student.java and ClassRoster.java.
Explanation / Answer
//please save as file name: Student.java
//compile (do not run) this file BEFORE ClassRoster.java file
//to test the files, you need to run only ClassRoster.java
public class Student
{
public String firstName;
public String lastName;
public int studentID;
public Student(String fn, String ln, int id)
{
firstName = fn;
lastName = ln;
studentID = id;
}
}
//---------------------------------------------------------------------------------
//please save as file name: ClassRoster.java
//Compile and run AFTER Student.java
import java.util.*;
public class ClassRoster
{
public static void main (String[] args)
{
LinkedList<Student> list=new LinkedList<Student>();
//generating 20 random student names and ids
int r;
//manually adding 3 names and id's .
//If you add more here, make sure to change the value of the size variable below
int size=3;
list.add(new Student("Sam","Jackson",13345));
list.add(new Student("Jack","Bauer",3456));
list.add(new Student("Tony","Stark",8893));
/* commenting this part out
for(int i=0;i<size;i++)
{
r=(int)(Math.random()*100);
list.add(new Student("FirstName"+r,"LastName"+r,r));
}
*/
//printing list in forward
Student tmp;
System.out.println("Printing LinkedList in Order of Insertion");
for(int i=0;i<size;i++)
{
tmp = list.get(i);
System.out.println("Name: "+tmp.firstName+" "+tmp.lastName+" ID: "+tmp.studentID);
}
System.out.println();
System.out.println("Printing LinkedList in REVERSE Order");
for(int i=size-1;i>=0;i--)
{
tmp = list.get(i);
System.out.println("Name: "+tmp.firstName+" "+tmp.lastName+" ID: "+tmp.studentID);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.