Average method in java Add an average method to the MyLinkedListL3 class in the
ID: 3657019 • Letter: A
Question
Average method in java Add an average method to the MyLinkedListL3 class in the program showing below. your average method should return the average of all the x data on the list. if the list is null, your average method should throws a MyLinkedListException. your average method should return a double value. test it against null list and non-null list. { public static void main(String[] args) { MyLinkedListL3 list = new MyLinkedListL3(); list.addFirst(1); list.addFirst(2); list.addFirst(3); System.out.println("Numbers on list"); list.traverse(); } } //============================================== class MyLinkedListL3 // copy of MyLinkedList in Fig. 15.4 { private class Node { private Node link; private int x; } //---------------------------------- private Node first = null; //---------------------------------- public void addFirst(int d) { Node newNode = new Node(); newNode.x = d; newNode.link = first; first = newNode; } //---------------------------------- public void traverse() { Node p = first; while (p != null) { System.out.println(p.x); p = p.link; } } }Explanation / Answer
public double(List list) { double avg = 0; if(list.size() == 0) { throw new MyLinkedListException(); } else { int n=0, sum =0; for(MyLinkedListL3 temp: list) { sum = sum + temp.getX(); n++; } avg = (double)sum/n; } return avg; }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.