-
-
Save NikoZBK/4af2f7f0a8254649bd5b1c99fdcfb1f5 to your computer and use it in GitHub Desktop.
ComputeDeviation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Name: Nikolay Ostroukhov | |
* Date: 11/9/19 | |
* Course Number: 111 | |
* Course Name: CSC | |
* Problem Number: Homework 8 -- Compute Standard Deviation | |
* Email: noostroukhov@student.stcc.edu | |
* Computes standard deviation of a file | |
*/ | |
package hw8; | |
import java.io.IOException; | |
import java.net.URL; | |
import java.util.Scanner; | |
public class ComputeDeviation { | |
final static String TITLE = "Niko's Standard Deviation Calculator"; | |
final static String CONTINUE_PROMPT = "\nPerform another calculation? [y/N] "; | |
// ********************************************** | |
private static double power(double x, int exp) { | |
double result = 1.0; | |
for (int i = 1; i <= exp; i++) | |
result *= x; | |
return result; | |
} | |
private static double deviation(double[] x) { | |
double result = 0.0; | |
for (int i = 0; i < x.length; i++) | |
result += power(x[i] - mean(x), 2); | |
result /= x.length - 1; | |
return result = Math.sqrt(result); | |
} | |
private static double mean(double[] x) { | |
double result = 0.0; | |
for (int i = 0; i < x.length; i++) | |
result += x[i]; | |
return result /= x.length; | |
} | |
private static double[] populateArray(Scanner sc) { | |
int count = sc.nextInt(); | |
double[] result = new double[count]; | |
for (int i = 0; i < count; i++) | |
result[i] = sc.nextDouble(); | |
return result; | |
} | |
// ********************************************** | |
private static void process(Scanner sc, String args[]) throws IOException { | |
System.out.print("Enter filename: "); | |
URL url = new URL("https://cs.stcc.edu/~silvestri/csc111/" + sc.nextLine()); | |
Scanner scanURL = new Scanner(url.openStream()); | |
double[] arr = populateArray(scanURL); | |
double mean = mean(arr); | |
double deviation = deviation(arr); | |
System.out.printf("Mean: \t\t%.3f\nDeviation: \t%.3f", mean, deviation); | |
scanURL.close(); | |
} | |
// ********************************************** | |
private static boolean doThisAgain(Scanner sc, String prompt) { | |
System.out.print(prompt); | |
String doOver = sc.nextLine(); | |
return doOver.trim().equalsIgnoreCase("Y"); | |
} | |
// ********************************************** | |
public static void main(String args[]) throws IOException { | |
System.out.println("Welcome to " + TITLE); | |
Scanner sc = new Scanner(System.in); | |
do { | |
process(sc, args); | |
} while (doThisAgain(sc, CONTINUE_PROMPT)); | |
sc.close(); | |
System.out.println("Thank you for using " + TITLE); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment