The program is complete except that I have removed the body of the method for av
ID: 3707357 • Letter: T
Question
The program is complete except that I have removed the body of the method for averaging the numbers in the linked list.. Given the following class for the nodes in a linked list: public class Node { ... public Node getNext() {...} // return next field public int getData() {...} // returns data } Assuming that the variable head points to (i.e. contains the address of) the first node of a linked list, write the statements to find the average of all data values in the linked list. For example, average() will return something like "avg: 2.67" or "Empty". The average should be returned as a string with exactly two digits of decimal accuracy, or Empty if the list is empty. Your statements will be inserted inside a method like the following: public String average() { // Whatever statements you provide in response to this question will // be inserted here BY THE SYSTEM and then compiled and tested as part of // a larger program which does many other things with the linked list }
Explanation / Answer
//import java.text.DecimalFormat;
public String average() {
Node root ; // Assign root node or first node in linked list to root
if (root == null) {
return "Empty";
} else {
Double avg = 0.00;
double sum = 0;
int count = 0;
while (root != null) {
sum += root.getData();
count++;
root = root.getNext();
}
avg = sum / count;
//Used DecimalFormat for two digits of decimal accuracy
DecimalFormat df = new DecimalFormat("#.##");
return "avg: " + df.format(avg);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.