Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.Scanner;
- public class StandartDeviation {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- //First we enter the number of players and check if the input is correct.
- System.out.println("Enter number of players: ");
- String number = scanner.nextLine();
- while (number.matches("\\D+")) {
- System.out.println("Number must be integer. Try again.");
- number = scanner.nextLine();
- }
- int n = Integer.parseInt(number);
- //Then we create the score array and check it.
- double[] scores = new double[n];
- boolean isDigit = true;
- System.out.println("Enter scores separated by ','");
- String[] scoresLine = scanner.nextLine().split(",".trim());
- for (int i = 0; i < n; i++) {
- if (!scoresLine[i].matches("\\d+")) {
- System.out.printf("The score %d is entered incorrectly.%n", i + 1);
- isDigit = false;
- break;
- } else scores[i] = Double.parseDouble(scoresLine[i]);
- }
- while (n != scores.length || n != scoresLine.length || !isDigit) {
- System.out.println("Your input is wrong. Try again.");
- scoresLine = scanner.nextLine().split(",".trim());
- }
- System.out.printf("The fastest is %.2f%nThe slowest is %.2f%nThe average is %.2f%nThe standard deviation is %.2f%n",
- theFastest(scores), theSlowest(scores), average(scores), standardDeviation(scores));
- }
- public static double theFastest(double... arr) {
- double fastest = arr[0];
- for (int i = 0; i < arr.length; i++) {
- if (arr[i] > fastest) {
- fastest = arr[i];
- }
- }
- return fastest;
- }
- public static double theSlowest(double... arr) {
- double slowest = arr[arr.length - 1];
- for (int i = 0; i < arr.length; i++) {
- if (arr[i] < slowest) {
- slowest = arr[i];
- }
- }
- return slowest;
- }
- public static double average(double... arr) {
- double sum = 0;
- double average = 1;
- for (int i = 0; i < arr.length; i++) {
- sum += arr[i];
- average = sum / arr.length;
- }
- return average;
- }
- public static double standardDeviation(double... arr) {
- double sd1 = 0;
- double sd = 0;
- for (int i = 0; i < arr.length; i++) {
- sd1 += Math.pow(arr[i] - average(arr), 2);
- sd = Math.sqrt(sd1 / arr.length);
- }
- return sd;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement