Question: PLEASE HELP IN JAVA: Using the input file called StudentInputFile.txt, input these students into a linked list sorted according to their age. In each case
PLEASE HELP IN JAVA:
Using the input file called StudentInputFile.txt, input these students into a linked list sorted according to their age. In each case I made the student's last name their age as a string so when the input file says "John" "Twenty" 20 this means the student's first name is John, last name is Twenty, and age is 20. This is so that when you output the list you can easily tell if it is sorted by looking at the last names.
I have given you a class called Student. You will have to add a compareTo method so this class can implement comparable. Do NOT add a getAge() method to the class. In main I want you to be able to compare two Student objects.
Do not use an array or any other data structure other than the list. Do not add them to the list and then sort the list. I want you to add each node to the list in the "correct" place in order to keep the list sorted as you are building it. Then output the contents of the list.
studentInputFile.txt:
Marty Twenty 20
Elizabeth Fifty 50
Christy Nineteen 19
Graham TwentyFive 25
Doris FiftyOne 51
Eleanor ThirtyFive 35
Mark Nineteen 19
Margaret Forty 40
Jessica ThirtyOne 31
What I have so far:
class Student{ private String name; private int age; public Student(String n, int a) { name = n; age=a; } public String toString() { return name; } } public static Node InsertAtFront(Node head, Node temp) { if(head==null)head=temp; else{ temp.next=head; head=temp; } return head; } public static Node InsertAtEnd(Node head, Node temp) { if(head==null)head=temp; else{ Node curr=head; while(curr.next!=null) { curr=curr.next; } curr.next=temp; } return head; } public static Node InsertAfter(Node head, Node temp, Node newNode) { if(temp==null)head=newNode; else{ newNode.next=temp.next; temp.next=newNode; } return head; } public static class Node { Object item; Node next; Node(Object newItem) { item = newItem; next=null; } Node(Object newItem, Node nextNode) { item = newItem; next=nextNode; } }
public static void main(String[] args) { // Student []A={new Student("Mary"); Node head=null, curr=null, tail=null; int[] intArr={5, 4, 3, 2, 1, 9, 8, 7, 6}; for(int i=0; intArr.length>i; i++){ //create a node and add to list Node temp = new Node(intArr[i]); head = addList(head, temp); } PrintList(head); } public static void PrintList(Node head) { Node curr=head; int m; while(curr !=null) { m= (int) curr.item; System.out.println(m); curr=curr.next; //end while } } public static Node addList(Node list, Node temp) { if(list == null) list = temp; else{temp.next = list; list = temp;} return list; } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
