SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Generics And The Arraylist Class
Exercise:
Programming Projects
Question:4 | ISBN:9780132830317 | Edition: 5

Question

Write a generic class, MyMathClass, with a type parameter T where T is a numeric object type (e.g., Integer, Double, or any class that extends java.lang.Number ). Add a method named standardDeviation that takes an ArrayList of type T and returns as a double the standard deviation of the values in the ArrayList. Use the doubleValue () method in the Number class to retrieve the value of each number as a double. Refer to Programming Project 6.5 for a definition of computing the standard deviation. Test your method with suitable data. Your program should generate a compile-time error if your standard deviation method is invoked on an ArrayList that is defined for nonnumeric elements (e.g., Strings ).


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

public class MyMathClass<T extends Number> 
{	
	public double standardDeviation(ArrayList<T> numbers)
	{
		double Average = 0;
		for(int i = 0; i < n.size(); i++)
		{
			average += n.get(i).doubleValue();
		}
		
		Average /= n.size();
		
		double stdDeviation = 0;
		for(int j = 0; j < n.size(); j++)
		{
			stdDeviation += (n.get(j).doubleValue() – Average)  *(n.get(j).doubleValue() – Average);
		}

		stdDeviation = Math.sqrt(stdDeviation / n.size());
		return stdDeviation;
	}
}


import java.util.*;

public class TestMath
{
	public static void main(String args[])
	{

        ArrayList<Double> doublevalues = new ArrayList<Double>();
		ArrayList<Integer> integers = new ArrayList<Integer>();
		
		for(double i = 1; i < 5.5; i += 0.5)
			doublevalues.add(i);
		
		for(int j = 1; j < 10; j++)
			integers.add(j);
			
		MyMathClass<Double> object1 = new MyMathClass<Double>();
		System.out.println("Standard deviation for double array: " +  object1.standardDeviation(doublevalues));
		
MyMathClass<Integer> object2 = new MyMathClass<Integer>();
		System.out.println("Standard deviation for integer array: " + object2.standardDeviation(integers));
	}
}   

 

0 0

Discussions

Post the discussion to improve the above solution.