Instructions
Requirements and Specifications
Source Code
import java.util.Scanner;
public class TestScore {
private static Scanner scanner;
public static int readStudentNum() {
System.out.print("Enter number of students: ");
while(true) {
try {
int n = Integer.parseInt(scanner.nextLine());
if (n <= 0) {
throw new IllegalArgumentException();
}
return n;
}
catch (Exception e) {
System.out.print("Invalid try again: ");
}
}
}
public static void readScores(String[] names, double[] scores) {
int n = names.length;
System.out.println("Enter the name and test score for the students:");
for (int i = 0; i
String[] parts = scanner.nextLine().trim().split("\\s+");
names[i] = parts[0];
scores[i] = Math.round(Double.parseDouble(parts[1]) * 100) / 100.0;
}
}
public static double average(double[] scores) {
int n = scores.length;
double sum = 0.0;
for (double score : scores) {
sum += score;
}
return sum / n;
}
public static double variance(double[] scores) {
int n = scores.length;
double avg = average(scores);
double sum = 0.0;
for (double score : scores) {
double diff = score - avg;
sum += diff * diff;
}
return sum / (n - 1);
}
public static void sort(String[] names, double[] scores) {
int n = names.length;
for (int i = 0; i
for (int j = 0; j
if (scores[j] > scores[j+1]) {
String stmp = names[j];
names[j] = names[j+1];
names[j+1] = stmp;
double dtmp = scores[j];
scores[j] = scores[j+1];
scores[j+1] = dtmp;
}
}
}
}
public static void main(String[] args) {
scanner = new Scanner(System.in);
int n = readStudentNum();
String[] names = new String[n];
double[] scores = new double[n];
readScores(names, scores);
System.out.println("***here is what I have for your data***");
for (int i = 0; i
System.out.println(names[i] + " " + scores[i]);
}
sort(names, scores);
System.out.println("***Sorted data***");
for (int i = 0; i
System.out.println(names[i] + " " + scores[i]);
}
System.out.println("Average = " + Math.round(average(scores) * 100) / 100.0);
System.out.println("Variance = " + Math.round(variance(scores) * 100) / 100.0);
}
}