Question

In: Computer Science

In the previous question, you designed a simple algorithm to create a class list application. In...

In the previous question, you designed a simple algorithm to create a class list application. In this question, you
will implement the same application in Java. To do this, you will need a working version of a Student ADT, a List
ADT, and the List Iterator. You may start with your own Student ADT, or you can start from the solutions to
Assignment 2. You will be given a working version of a List ADT.
Recall that your application does the following:
• Create a class list of students
• Display every Student record in the class list to the console.
• Give every student a bonus mark on the final exam. It does not matter how much of a bonus you give.
• Display every Student record in the class list to the console, to show the changes to the records.
You must store Student objects in a List, using the given List ADT.
You are to use the List Iterator for any task that requires looking at every element in a list (the last two items
above).
Here’s a guide for you to help you manage this task.
1. Download the BasicLinkedList.java and List.java files from Moodle.
2. Obtain the StudentADT.java and Student.java files from either your solution or the model solution of assignment
3. Create a new application class called ClassListApp.java, that contains a main method. Make sure that you
include import java.util.*; on the top of the file.
4. Take your design for Exercise 1, and copy it into ClassListApp.java, as comments. Implement the design in
steps (not all at once). Every time you have a step implemented, compile and test.

Here are the java source file already given

List.java

import java.util.Iterator;

/**
* Defines the interface to a list collection.
* The implementation of the list is hidden.
*
*/
public interface List<E> extends Iterable<E>
{
  
/**
Pre:
Post: the list is unchanged.
* Return: true if this list contains no elements; false otherwise
*/
public boolean isEmpty();
  
  
/**
Pre:
Post: the list is unchanged.
* Return: the number of elements in this list.
*/
public int size();
  
  
/**
* Check if an element exists in the list
Pre:
Post: the list is unchanged.
Return: true if the specified element is found in this list and
false otherwise. Throws an EmptyCollectionException if the list
is empty.
*/
public boolean contains (E targetElement);
  
/**
Deletes the first element in this list and returns a reference
to it. Throws an EmptyCollectionException if the list is empty.
Pre:
Post: the first element is removed from the list
Return: a reference to the removed element
*/
public E deleteHead();
  
/**
Removes the last element in this list and returns a reference
to it. Throws an EmptyCollectionException if the list is empty.
Pre:
Post: the last element is removed from the list
Return: a reference to the removed element
*/
public E deleteTail();
  
/**
Removes the first instance of the specified element from this
list and returns a reference to it. Throws an EmptyCollectionException
if the list is empty. Throws a ElementNotFoundException if the
specified element is not found in the list.
Pre: targetElement :: E, the target element to be removed
Post: the element is removed from the list
Return: a reference to the removed element
*/
public E deleteElement(E targetElement);


/**
Insert a new node to the head of the list.
Pre: item :: E, content in the new node
Post: new node is inserted to the head of the list
Return: nothing
*/
public void insertHead(E item);
  
/**
Insert a new node to the end of the list.
Pre: item :: E, content in the new node
Post: new node is inserted to the end of the list
Return: nothing
*/
public void insertTail(E item);
  
  
/**
Insert a new node at a specific position in the list.
Pre: item :: E, content in the new node
position :: the position of the new node
Post: new node is inserted at position in the list
Return: nothing
*/
public void insertAtPosition (E item, int position);
  
  
/**
Retrive the element at a specific position in the list.
Pre: position :: Integer, a position in the list
Post: the list is unchanged
Return: the element at the position
*/
public E get(int position);
  
  
  
/**
* Useful method for pretty print for atomic data
Pre:
Post: the list is unchanged.
Return: Returns a string representation of this list.
*/
public String toString();
  
  
/**
* Returns an iterator for the elements in this list.
*
* @return an iterator over the elements in this list
*/
public Iterator<E> iterator();
  
  }

Student.java

/**
* Defines the interface to the student ADT.
*
*/
public interface Student {

/**
displayStudentRecord()
Pre:
Post: displays Student info
Return: nothing
*/
public void displayStudentRecord();
  
  
/**
Algorithm changeAssignmentGradeForStudent(asnNum,grade)
Pre: asnNum :: Integer, the index of the assignment to grade
grade :: double, the amount to change the grade
Post: If the index is sensible, the appropriate grade is changed
(this method allows grades to be changed arbitrarily)
Return: true if the change was made, false otherwise
*/
public boolean changeAssignmentGradeForStudent (int asnNum, double grade);

/**
Algorithm changeExamGradeForStudent(grade)
Pre: grade :: double, the amount to change the grade
Post: the exam grade is changed
(this method allows grades to be changed arbitrarily)
Return: nothing
*/
public void changeExamGradeForStudent(double grade);
  
}

StudentADT.java

public class StudentADT implements Student {
  
private String firstName;
private String lastName;
private int stNum;
private double [] agrades;
private double egrade;

  
/**
Algorithm StudentADT(firstNm, lastNm, stNo, asn1Grade, asn2Grade, asn3Grade, examGrade)
Constructor to create a student object
Pre: firstNm, lastNm :: String
stNo :: integer
asn1Grade, asn2Grade, asn3Grade :: double
examGrade :: double
Post: allocates memory on the heap for a new Student object
Return: a new Student object, with all fields filled in
*/
  
public StudentADT(String firstNm, String lastNm, int stNo, double asn1Grade, double asn2Grade, double asn3Grade, double examGrade){   
this.firstName = firstNm;
this.lastName = lastNm;
this.stNum = stNo;
this.agrades = (double[]) new double[3];
this.agrades[0] = asn1Grade;
this.agrades[1] = asn2Grade;
this.agrades[2] = asn3Grade;
this.egrade = examGrade;
}

/**
Algorithm displayStudentRecord()
Pre:
Post: displays Student info
Return: nothing

*/
public void displayStudentRecord() {
System.out.println("Record for " + this.lastName + ", " + this.firstName + " (" + this.stNum + ") ");
System.out.println("Assignment grades");
for (int i = 0 ; i <= 2; i ++)
System.out.println(this.agrades[i]);
System.out.println("Exam grade: " + this.egrade);
}
  
/**
Algorithm changeAssignmentGradeForStudent(asnNum,grade)
Pre: asnNum :: Integer, the index of the assignment to grade
grade :: double, the amount to change the grade
Post: If the index is sensible, the appropriate grade is changed
(this method allows grades to be changed arbitrarily)
Return: true if the change was made, false otherwise
*/
public boolean changeAssignmentGradeForStudent (int asnNum, double grade) {
  
if (asnNum < 0 || asnNum > 2)
return false;
else {
this.agrades[asnNum] = this.agrades[asnNum] + grade;
return true;
}
}
  
  
/**
Algorithm changeExamGradeForStudent(grade)
Pre: grade :: double, the amount to change the grade
Post: the exam grade is changed
(this method allows grades to be changed arbitrarily)
Return: nothing
*/

public void changeExamGradeForStudent(double grade) {
this.egrade = this.egrade + grade;
}

  
}

Solutions

Expert Solution

import java.util.Iterator;

interface List<E> extends Iterable<E> {

    public boolean isEmpty();

    public int size();

    public boolean contains(E targetElement);

    public E deleteHead();

    public E deleteTail();

    public E deleteElement(E targetElement);

    public void insertHead(E item);

    public void insertTail(E item);

    public void insertAtPosition(E item, int position);

    public E get(int position);

    public String toString();

    public Iterator<E> iterator();

}

public class BasicLinkedList<E> implements List<E>, Iterable<E> {

    private Node<E> head;
    private Node<E> tail;
    private int numElements;

// basic constructor
    public BasicLinkedList() {
        head = null;
        tail = null;
        numElements = 0;
    }

    public boolean isEmpty() {
        return (numElements == 0);
    }

    public int size() {
        return numElements;
    }

    public boolean contains(E targetElement) {
        if (isEmpty())
            throw new IllegalStateException("List is empty and there are no elements to check");

        boolean found = false;
        Node<E> current = head;

        while (current != null && !found)
            if (targetElement.equals(current.getNodeItem()))
                found = true;
            else
                current = current.getNextNode();

        return found;
    }

    public E deleteHead() {
        if (isEmpty())
            throw new IllegalStateException("List is empty and there are no elements to delete");

        Node<E> result = head;
        head = head.getNextNode();
        if (head == null)
            tail = null;
        numElements--;

        return result.getNodeItem();
    }

    public E deleteTail() {
        if (isEmpty())
            throw new IllegalStateException("List is empty and there are no elements to delete");

        Node<E> previous = null;
        Node<E> current = head;

        while (current.getNextNode() != null) {
            previous = current;
            current = current.getNextNode();
        }

        Node<E> result = tail;
        tail = previous;
        if (tail == null) // only one element in list
            head = null;
        else
            tail.setNextNode(null);
        numElements--;

        return result.getNodeItem();
    }

    public E deleteElement(E targetElement) {
        if (isEmpty())
            throw new IllegalStateException("List is empty and there are no elements to delete");

        boolean found = false;
        Node<E> previous = null;
        Node<E> current = head;

        while (current != null && !found) {
            if (targetElement.equals(current.getNodeItem()))
                found = true;
            else {
                previous = current;
                current = current.getNextNode();
            }
        }

        if (!found)
            throw new IllegalStateException("Item is not found in the list");

        if (size() == 1) // only one element in the list
            head = tail = null;
        else if (current.equals(head)) // target is at the head
            head = current.getNextNode();
        else if (current.equals(tail)) // target is at the tail
        {
            tail = previous;
            tail.setNextNode(null);
        } else // target is in the middle
            previous.setNextNode(current.getNextNode());

        numElements--;

        return current.getNodeItem();
    }

    public void insertHead(E item) {
        Node<E> newNode = new Node<E>(item);

        newNode.setNextNode(head);
        head = newNode;

        if (tail == null) { // special case: when list is empty
            tail = newNode;
        }

        numElements++;
    }

    public void insertTail(E item) {
        if (head == null) { // special case: when list is empty
            head = new Node<E>(item);
            tail = head;
        } else {
            Node<E> newLastNode = new Node<E>(item);
            tail.setNextNode(newLastNode);
            tail = newLastNode;
        }
        numElements++;
    }

    public void insertAtPosition(E item, int position) {
        if (size() < position) {
            throw new IllegalStateException("The LinkedList is smaller than the position");
        }

        Node<E> currentNode = head;

        // start at 2 because we are already on the head node
        for (int i = 2; i < position; i++) {
            currentNode = currentNode.getNextNode();
        }

        // serves the link chain and reconnects with the new node
        Node<E> newNode = new Node<E>(item);
        Node<E> next = currentNode.getNextNode();
        currentNode.setNextNode(newNode);
        newNode.setNextNode(next);

        numElements++;
    }

    public E get(int position) {
        if (head == null) {
            throw new IllegalStateException("The LinkedList is empty and there are no items to get");
        }

        Node<E> currentNode = head;
        for (int i = 1; i < position; i++) {
            if (i == position) {
                return currentNode.getNodeItem();
            }

            currentNode = currentNode.getNextNode();
        }

        // if we didn't find it, return null
        return null;
    }

    public String toString() {
        StringBuffer contents = new StringBuffer();
        Node<E> curNode = head;

        while (curNode != null) {
            contents.append(curNode.getNodeItem());
            curNode = curNode.getNextNode();

            if (curNode != null) {
                contents.append(", ");
            }
        }

        return contents.toString();
    }

    public Iterator<E> iterator() {
        return new LinkedListIterator();
    }

//a class inside a class
    private class Node<E> {
        private Node<E> next;
        private E nodeItem;

        // constructor
        public Node(E item) {
            this.next = null;
            this.nodeItem = item;
        }

        public void setNextNode(Node<E> nextNode) {
            this.next = nextNode;
        }

        public Node<E> getNextNode() {
            return next;
        }

        public E getNodeItem() {
            return nodeItem;
        }
    }

    private class LinkedListIterator implements Iterator<E> {
        private int iteratorModCount; // the number of elements in the collection
        private Node<E> current; // the current position

        public LinkedListIterator() {
            current = head;
        }

        public boolean hasNext() {
            return (current != null);
        }

        public E next() {
            if (!hasNext())
                throw new IllegalStateException("Reach the end of the list");

            E result = current.getNodeItem();
            current = current.getNextNode();
            return result;
        }

    }


    public static void main(String args[]) {
        List<Student> myList = new BasicLinkedList<>();
        myList.insertTail(new StudentADT("F1", "L1", 1, 40, 50, 60, 70));
        myList.insertTail(new StudentADT("F2", "L2", 2, 50, 50, 90, 40));
        myList.insertTail(new StudentADT("F3", "L3", 3, 70, 90, 60, 50));

        // Your application uses the List Iterator to display every Student record
        Iterator<Student> studentIter = myList.iterator();

        while(studentIter.hasNext()) {
            studentIter.next().displayStudentRecord();
        }

        studentIter = myList.iterator();
        System.out.println("==============================");
        while(studentIter.hasNext()) {
            studentIter.next().changeExamGradeForStudent(10);
        }

        studentIter = myList.iterator();

        while(studentIter.hasNext()) {
            studentIter.next().displayStudentRecord();
        }

    }
}

interface Student {

    public void displayStudentRecord();

    public boolean changeAssignmentGradeForStudent(int asnNum, double grade);

    public void changeExamGradeForStudent(double grade);

}

class StudentADT implements Student {

    private String firstName;
    private String lastName;
    private int stNum;
    private double[] agrades;
    private double egrade;

    public StudentADT(String firstNm, String lastNm, int stNo, double asn1Grade, double asn2Grade, double asn3Grade,
            double examGrade) {
        this.firstName = firstNm;
        this.lastName = lastNm;
        this.stNum = stNo;
        this.agrades = (double[]) new double[3];
        this.agrades[0] = asn1Grade;
        this.agrades[1] = asn2Grade;
        this.agrades[2] = asn3Grade;
        this.egrade = examGrade;
    }

    public void displayStudentRecord() {
        System.out.println("Record for " + this.lastName + ", " + this.firstName + " (" + this.stNum + ") ");
        System.out.println("Assignment grades");
        for (int i = 0; i <= 2; i++)
            System.out.println(this.agrades[i]);
        System.out.println("Exam grade: " + this.egrade);
    }

    public boolean changeAssignmentGradeForStudent(int asnNum, double grade) {

        if (asnNum < 0 || asnNum > 2)
            return false;
        else {
            this.agrades[asnNum] = this.agrades[asnNum] + grade;
            return true;
        }
    }

    public void changeExamGradeForStudent(double grade) {
        this.egrade = this.egrade + grade;
    }

}

Please upvote, as i have given the exact answer as asked in question. Still in case of any concerns in code, let me know in comments. Thanks!


Related Solutions

Create a Java windows application to manage a list of stocks 1. Add a class Stock...
Create a Java windows application to manage a list of stocks 1. Add a class Stock with the following fields: companyName, pricePerShare, numberOfShares (currently owned) and commission (this is the percent you pay a financial company when you purchase or sell stocks. Add constructor, getters and methods: ***purchaseShares (method that takes the number of shares purchased, updates the stock and return the cost of purchasing these shares make sure to include commission. ***sellShares (method that takes the number of shares...
Question 1: Using Python 3 Create an algorithm The goal is to create an algorithm that...
Question 1: Using Python 3 Create an algorithm The goal is to create an algorithm that can sort a singly-linked-list with Merge-sort. The program should read integers from file (hw-extra.txt) and create an unsorted singly-linked list. Then, the list should be sorted using merge sort algorithm. The merge-sort function should take the head of a linked list, and the size of the linked list as parameters. hw-extra.txt provided: 37 32 96 2 25 71 432 132 76 243 6 32...
Build a simple list implementation that uses arrays to store the values. Create a class SimpleArrayList...
Build a simple list implementation that uses arrays to store the values. Create a class SimpleArrayList with a public constructor that initializes the list using a passed array of Object references. Assert that the passed array is not null. Next, implement: 1)Object get(int), which takes an int index and returns the Object at that index 2)void set(int, Object), which takes an int index and an object reference and sets that value at the index to the passed reference Both your...
Binary Search Algorithm a.) Create a Java application that utilizes the "Binary Search Algorithm" presented in...
Binary Search Algorithm a.) Create a Java application that utilizes the "Binary Search Algorithm" presented in chapter 19 (NOT Java's pre-built binarySearch() method from imported Java library) to search for an integer in a random array of size 30 in the range of 0 to 1000 inclusive. You should use Java's random number generator to randomize the numbers in your array. b.) The application's main() method should display unsorted array and sorted array, prompt user for a search key, allow...
Create a simple C++ application that will exhibit concurrencyconcepts. Your application should create two threads...
Create a simple C++ application that will exhibit concurrency concepts. Your application should create two threads that will act as counters. One thread should count up to 20. Once thread one reaches 20, then a second thread should be used to count down to 0. For your created code, provide a detailed analysis of appropriate concepts that could impact your application. Specifically, address:Performance issues with concurrencyVulnerabilities exhibited with use of stringsSecurity of the data types exhibited.
Create a List Create a class that holds an ordered list of items. This list should...
Create a List Create a class that holds an ordered list of items. This list should have a variable size, most importantly this class should implement the interface SimpleArrayList. Feel free to add as many other functions and methods as needed to your class to accomplish this task. In other words, you have to write the code for each of the functions specified in the SimpleArrayList interface. You are not allowed to use any 3rd party data structures or libraries...
Below is a definition of the class of a simple link list. class Chain; class ChainNode...
Below is a definition of the class of a simple link list. class Chain; class ChainNode { friend class Chain; private: int data; ChainNode *link ; }; class Chain{ public: ... private: ChainNode *first; // The first node points. } Write a member function that inserts a node with an x value just in front of a node with a val value by taking two parameters, x and val. If no node has a val value, insert the node with...
Create a Java Application that implements a Selection sort algorithm to sort an array of 20...
Create a Java Application that implements a Selection sort algorithm to sort an array of 20 unsorted numbers. You should initiate this array yourself and first output the array in its original order, then output the array after it has been sorted by the selection sort algorithm. Create a second Java Application that implements an Insertion sort algorithm to sort the same array. Again, output the array in its original order, then output the array after it has been sorted...
Create a Java Application that implements a Selection sort algorithm to sort an array of 20...
Create a Java Application that implements a Selection sort algorithm to sort an array of 20 unsorted numbers. You should initiate this array yourself and first output the array in its original order, then output the array after it has been sorted by the selection sort algorithm.
In Java in previous question #1, you created a method called isDNAvalid() in the DNA class....
In Java in previous question #1, you created a method called isDNAvalid() in the DNA class. You probably looped through the entire sequence one character at a time (using charAt() method of the String class), and check if the character is 'A', 'T', 'G', or 'C'. If it is not one of these four characters, the sequence contains an invalid base. Please re-create the isDNAvalid() method using a character pattern and the regular expression to validate the DNA sequence. previous...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT