Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*--------------------------
- | Tyson Holub |
- | CSCI 111 |
- | Computing Deviation |
- | 03/29/11 |
- | Problem 6.11 |
- | tjholub@student.stcc.edu |
- --------------------------*/
- //Numbers Numbers Numbers
- import java.util.Scanner;
- import java.util.ArrayList;
- public class Deviation {
- public static void main(String[] args) {
- Numbers numbers = getNumbers();
- numbers.printNumbers();
- System.out.println("\n"+numbers.size()+" values were read from scanner.");
- System.out.println("The largest number is "+numbers.largestNum);
- System.out.printf("The standard deviation is %.4f\n",numbers.deviation());
- System.out.printf("The mean is %.4f\n",numbers.mean());
- }
- private static Numbers getNumbers(){
- Scanner input = new Scanner(System.in);
- //Numbers class extends ArrayList. Ignore first size setting input
- //if inputting via keyboard, enter first value twice.
- input.nextInt();
- Numbers numbers = new Numbers();
- //break input with any non numeric char if not reading from file
- while(input.hasNextDouble())
- numbers.nextNumber(input.nextDouble());
- return numbers;
- }
- }
- //this class does not support a full extension
- //given ArrayList has methods that could alter
- //the List. Just spicing things up for practice.
- @SuppressWarnings("rawtypes")
- class Numbers extends ArrayList{
- private static final long serialVersionUID = 3527688495657167072L;
- private int count = 0;
- private double sum = 0;
- private double mean = 0;
- public double largestNum = 0;
- //in case largest value is removed.
- private void findLargest(){
- largestNum = 0;
- for(int i=0;i<count;i++){
- if(Double.parseDouble(get(i).toString()) > largestNum)
- largestNum = Double.parseDouble(get(i).toString());
- }
- }
- public Numbers(){
- super();
- }
- public void printNumbers(){
- int spacing = String.valueOf(largestNum).length();
- for(int i=0;i<count;i++){
- System.out.printf("%"+spacing+".1f "+((i+1) % 15 == 0 ? "\n" : ""),get(i));
- }
- }
- @SuppressWarnings("unchecked")
- public void nextNumber(double number){
- add(number);
- if(number > largestNum)
- largestNum = number;
- sum += number;
- count++;
- }
- //for good measure
- public void removeLast(){
- if(count != 0)
- {
- count--;
- sum -= Double.parseDouble(get(count).toString());
- if(Double.parseDouble(get(count).toString()) == largestNum)
- {
- remove(count);
- findLargest();
- }
- else
- remove(count);
- }
- }
- public double mean(){
- if(count != 0)
- mean = sum / count;
- else
- mean = 0;
- return mean;
- }
- public double deviation(){
- double deviation = 0;
- if(count > 1)
- {
- mean();
- for(int i=0;i<count;i++)
- deviation += (Math.pow(Double.parseDouble(get(i).toString()) - mean,2));
- deviation = Math.sqrt(deviation / (count - 1));
- }
- return deviation;
- }
- }
Add Comment
Please, Sign In to add comment