Java: Finding average of doubles in array - java

I'm working on an assignment for my intro to java class. Part of the assignment is reading in doubles from a text file into an array and then using a different method to calculate the average. So far I've read the doubles into the array but I'm not sure how to reference that array in another method to calculate the average. I've been searching online, but with no results probably because my poor terminology leads me to irrelevant answers. I get an error from netbeans that the symbol classGrades can't be found(because its only in the main method.) I tried defininig it as a global variable, but that didn't work and we haven't learned about those yet so there must be another way to do it.
To summarize: I don't know how to reference variables between methods.
Here is my code
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
public class GradeChecker {
public static void main(String[] args) {
// TODO code application logic here
double[] classGrades = new double[76];
double classAverage = calculateAverageGrade();
fillArray(classGrades);
for (int i = 0; i < classGrades.length; i++) {
System.out.println(classGrades[i]);
}
//System.out.print(Arrays.toString(classGrades));
System.out.print(classGrades.length);
}
public static void fillArray(double[] ary) {
try {
File arrayInput = new File("ClassGrades.txt");
Scanner in = new Scanner(arrayInput);
in.useDelimiter("\r\n");
int i = 0;
while (in.hasNextLine()) {
ary[i++] = in.nextDouble();
}
in.close();
} catch (Exception exception) {
System.out.println("Error: " + exception.getMessage());
}
}
private static double calculateAverageGrade(double[] classGrades) {
double gradeSum = 0;
double gradeAverage = 0;
for (int i = 0.0; i < classGrades.length; i++) {
gradeSum = gradeSum + classGrades[i];
}
gradeAverage = gradeSum/classGrades.length;
return gradeAverage;
}
}

You can pass array classGrades to the function:
double[] classGrades = new double[76];
double classAverage = calculateAverageGrade(classGrades);
Here:
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
public class GradeChecker {
public static void main(String[] args) {
// TODO code application logic here
double[] classGrades = new double[76];
double classAverage = calculateAverageGrade(classGrades);
fillArray(classGrades);
for (int i = 0; i < classGrades.length; i++) {
System.out.println(classGrades[i]);
}
//System.out.print(Arrays.toString(classGrades));
System.out.print(classGrades.length);
}
public static void fillArray(double[] ary) {
try {
File arrayInput = new File("ClassGrades.txt");
Scanner in = new Scanner(arrayInput);
in.useDelimiter("\r\n");
int i = 0;
while (in.hasNextLine()) {
ary[i++] = in.nextDouble();
}
in.close();
} catch (Exception exception) {
System.out.println("Error: " + exception.getMessage());
}
}
private static double calculateAverageGrade(double[] classGrades) {
double gradeSum = 0;
double gradeAverage = 0;
for (int i = 0; i < classGrades.length; i++) {
gradeSum = gradeSum + classGrades[i];
}
gradeAverage = gradeSum / classGrades.length;
return gradeAverage;
}
}

I have been edited your code.
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
public class GradeChecker {
public static void main(String[] args) {
// TODO code application logic here
double[] classGrades = new double[76];
fillArray(classGrades);
double classAverage = calculateAverageGrade(classGrades);
for (int i = 0; i < classGrades.length; i++) {
System.out.println(classGrades[i]);
}
//System.out.print(Arrays.toString(classGrades));
System.out.print(classGrades.length);
}
public static void fillArray(double[] ary) {
try {
File arrayInput = new File("ClassGrades.txt");
Scanner in = new Scanner(arrayInput);
in.useDelimiter("\r\n");
int i = 0;
while (in.hasNextLine()) {
ary[i++] = in.nextDouble();
}
in.close();
} catch (Exception exception) {
System.out.println("Error: " + exception.getMessage());
}
}
private static double calculateAverageGrade(double[] classGrades) {
double gradeSum = 0;
double gradeAverage = 0;
for (int i = 0; i < classGrades.length; i++) {
gradeSum = gradeSum + classGrades[i];
}
gradeAverage = gradeSum/classGrades.length;
return gradeAverage;
}
}
Please try this and let me know
EDIT 1
Lot of compilation issue.
fillArray called after finding calculateAverageGrade

Related

Attempting to utilize text captured from a PDF

I have an array called myArray that contains words separated by a space and trimmed from a PDF from the first page to the last page. I wrote a simple print array method that iterates through and prints each element one by one and it looks great!
Immediately after I have it go through another for loop for the length of the array and checks if (myArray[i].equals("(19)")) {//print something} When printing the array to the console it is clear that the value (19) exists in the array.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class Main {
static File file;
static PDFTextStripper textStripper;
static PDDocument pdDoc;
static COSDocument cosDoc;
static String parsedText;
static int sum = 0;
static String[] myArray;
static String[] events = {"400", "800", "1500",
"3000", "5000", "10000"};
public static void main(String[] args) {
//Read the PDF file into instance variable file
readFile();
try {
parsePDF(file);
} catch (IOException e) {
e.printStackTrace();
}
myArray = parsedText.split(" ");
removeWhiteSpace(myArray);
printArray(myArray);
//System.out.println();
String currentEvent = "";
for (int i = 0; i < myArray.length; i++) {
if (contains(myArray[i])) {
currentEvent = myArray[i];
}
if (!currentEvent.equals("")) {
if (myArray[i].charAt(0) == '(' && (myArray[i].charAt(myArray[i].length() - 1) == ')')) {
String formatedRunners = "";
//It is possible to see some numbers such as (19)) or (19)
if (containsCharacter(myArray[i], ')') == 2) {
formatedRunners = myArray[i].substring(1, myArray[i].length() - 2);
} else {
formatedRunners = myArray[i].substring(1, myArray[i].length() - 1);
}
int numberOfRunners = Integer.parseInt(formatedRunners);
int distance = Integer.parseInt(currentEvent);
sum += numberOfRunners * distance;
//reset currentEvent
currentEvent = "";
}
}
}
//Print total distance in meters
System.out.println(sum + " meters");
//Convert meters to miles using the following equation: meters / 1609.344
System.out.println( Math.round((sum / 1609.344)) + " miles");
}
public static void readFile() {
Scanner c = new Scanner(System.in);
System.out.println("Enter a file path: ");
String filePath = c.nextLine();
file = new File(filePath);
}
public static void parsePDF(File file) throws IOException {
textStripper = new PDFTextStripper();
pdDoc = PDDocument.load(file);
//Parse PDF
textStripper.setStartPage(1);
//textStripper.setEndPage();
//Parsed String
parsedText = textStripper.getText(pdDoc);
}
public static boolean contains(String s) {
for (int i = 0; i < events.length; i++) {
if (s.equals(events[i])) {
return true;
}
}
return false;
}
public static void printArray(String[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
public static void removeWhiteSpace(String[] a) {
for (int i = 0; i < myArray.length; i++) {
if (myArray[i].equals("")) {
//Use some filler to avoid crashes when checking characters
myArray[i] = "NULL";
}
//Trim off all extra whitespace
myArray[i] = myArray[i].trim();
}
}
public static int containsCharacter(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
}
Here is what I want:
Parsing and trimming etc. (OK)
Iterating over myArray (in the main method) and detecting events (OK)
If an event occurred then the next value must be (Any number) like (19)
(NOK)
The number from step 3. will be used to compute another number
Reset the current event to repeat the process over and
over again.
It seems like that it is reading each event correctly but only picks up (19)) instead of (19).
There are several problems in you code (No Exceptionhandling, everything static, small bugs etc.) but I will focus on the major issue. (I removed the code which I did not change)
public class Main {
static File file;
static PDFTextStripper textStripper;
static PDDocument pdDoc;
static COSDocument cosDoc;
static String parsedText;
static int sum = 0;
static String[] myArray = {"Seeded", "3000", "random", 25, "(44)", "1500", "random", "(13)"};
static String[] events = {"400", "800", "1500", "3000", "5000", "10000", "200.000"};
public static void main(String[] args) {
//Read the PDF file into instance variable file
readFile();
try {
parsePDF(file);
} catch (IOException e) {
e.printStackTrace();
}
myArray = parsedText.split(" ");
removeWhiteSpace(myArray);
String currentEvent = "";
for (int i = 0; i < myArray.length; i++) {
if (contains(myArray[i])) {
currentEvent = myArray[i];
}
else if (!currentEvent.isEmpty()) {
Integer value = extractNumber(myArray[i]);
if (!myArray[i].isEmpty() && value!=null) {
int distance = Integer.parseInt(currentEvent);
sum += value.intValue() * distance;
//reset currentEvent
currentEvent = "";
}
}
}
//Print total distance in meters
System.out.println(sum + " meters");
//Convert meters to miles using the following equation: meters / 1609.344
System.out.println( Math.round((sum / 1609.344)) + " miles");
}
public static Integer extractNumber(String toCheck) {
Pattern r = Pattern.compile("^.*?\\([^\\d]*(\\d+)[^\\d]*\\).*$");
Matcher m = r.matcher(toCheck);
if(m.find()) {
return Integer.valueOf(m.group(1));
}
return null;
}
public static void removeWhiteSpace(String[] a) {
for (int i = 0; i < myArray.length; i++) {
//Trim off all extra whitespace
myArray[i] = myArray[i].trim();
}
}
The result is
151500 meters
94 miles

Read data from file, write result into a new file(java)

I need to read some txt file, get data from it, find out average numbers and then write them into another file. I've done pretty much everything , but can not write needed values in a new file.
public static double KronKesk(double a, double b, double c){
return (a/2+b+c/2)/2;
}
public static double KronKesk2(double[] b){
int jag = 0;
double sum = 0;
for (int i = 0; i < b.length; i++) {
jag++;
}
jag = jag - 1;
sum = ArraySum(b) - b[0] - b[b.length-1];
return (b[0]/2 + sum +b[b.length-1]/2)/jag;
}
public static double ArraySum(double[] a){
double sum = 0;
for (int i = 0; i < a.length; i++) {
sum = sum+a[i];
}
return sum;
}
public static void main(String[] args) {
try{
String filePath = "C:\\Users\\user\\Desktop\\TLU\\Semester 2\\ProgPohikursus\\temp";
BufferedReader br = new BufferedReader(new FileReader(filePath + ".txt"));
String rida;
List<Andmed> andmed = new ArrayList<>();
int ridaCount = 0;
while((rida = br.readLine()) != null){
String[] temp = rida.split(",");
Andmed andmed0 = new Andmed();
andmed0.setKuupaev(Double.valueOf(temp[0]));
andmed0.setTemp0(Double.valueOf(temp[1]));
andmed0.setTemp6(Double.valueOf(temp[2]));
andmed0.setTemp12(Double.valueOf(temp[3]));
andmed0.setTemp18(Double.valueOf(temp[4]));
andmed0.setTemp24(Double.valueOf(temp[5]));
andmed.add(andmed0);
ridaCount++;
}
System.out.println(andmed);
br.close();
File fout = new File(filePath + "_avgtemp" + ".txt");
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
Andmed andmed0 = new Andmed();
for (int i = 0; i < ridaCount; i++) {
double[] andmed1 = {andmed0.getTemp0(), andmed0.getTemp6(), andmed0.getTemp12(), andmed0.getTemp18(), andmed0.getTemp24()};
double[] andmedFaili = {andmed0.getKuupaev(), KronKesk2(andmed1)};
bw.write(Arrays.toString(andmedFaili) + "\n");
}
bw.close();
} catch(Exception ex){
ex.printStackTrace();
}
}
}
and another file with getters and setters:
public class Andmed {
private double k;
private double t0;
private double t6;
private double t12;
private double t18;
private double t24;
/*protected static List<Double> allTemp = new ArrayList<Double>();
public double tempListi(double t0, double t6, double t12, double t18, double t24){
allTemp.add(t0);
allTemp.add(t6);
allTemp.add(t12);
allTemp.add(t18);
allTemp.add(t24);
return 0;
}*/
public void setKuupaev(double k){
this.k = k;
}
public void setTemp0(double t0){
this.t0 = t0;
}
public void setTemp6(double t6){
this.t6 = t6;
}
public void setTemp12(double t12){
this.t12 = t12;
}
public void setTemp18(double t18){
this.t18 = t18;
}
public void setTemp24(double t24){
this.t24 = t24;
}
public double getKuupaev(){
return k;
}
public double getTemp0(){
return t0;
}
public double getTemp6(){
return t6;
}
public double getTemp12(){
return t12;
}
public double getTemp18(){
return t18;
}
public double getTemp24(){
return t24;
}
}
What I have in a first file is:
12.01,3,4,5,6,7,8
13.01,4,5,5,4,3,6
...
what i need to get into a new file:
12.01, chronological average of 6 previous numbers
what do I get for now is:
[0.0, 0.0]
[0.0, 0.0]
[0.0, 0.0]
Where is the mistake? :/
Thank You in advance!
In your for loop you are not using your list at all, but an empty andmed0 variable that you declared just before the loop.
Get rid of that variable and use the actual list :
// Andmed andmed0 = new Andmed(); // no need for that
for (int i = 0; i < ridaCount; i++) {
Andmed currentAndmed = andmed.get(i);
double[] andmed1 = {currentAndmed.getTemp0(), currentAndmed.getTemp6(), currentAndmed.getTemp12(), currentAndmed.getTemp18(), currentAndmed.getTemp24()};
double[] andmedFaili = {currentAndmed.getKuupaev(), KronKesk2(andmed1)};
bw.write(Arrays.toString(andmedFaili) + "\n");
}
Also note that you don't have to use a ridaCount variable to compute the size of the list, just call andmed.size() instead .
i.e :
for (int i = 0; i < andmed.size(); i++)
Finally as stated in the comments by #gilfernandes, you may simply use a foreach loop :
for(Andmed currentAndmed : andmed) {
double[] andmed1 = {currentAndmed.getTemp0(), currentAndmed.getTemp6(), currentAndmed.getTemp12(), currentAndmed.getTemp18(), currentAndmed.getTemp24()};
double[] andmedFaili = {currentAndmed.getKuupaev(), KronKesk2(andmed1)};
bw.write(Arrays.toString(andmedFaili) + "\n");
}

I am trying to create a method that calculates the averages of numbers in two arrays

import java.io.*;
import java.util.*;
public class Marks {
public static void main(String[] args) {
Marks r = new Marks();
double[] finalArray = r.openFile();
double[] finalArray2 = r.openFile2();
}
//ID's and first set of grades
private Scanner a;
public double[] openFile() {
ArrayList<String> list1 = new ArrayList<String>(7);
try {
a = new Scanner(new File("IR101.txt"));
} catch (Exception e) {
System.out.println("could not find file");
}
while (a.hasNextLine()) {
list1.add(a.nextLine());
}
String[] arrayOne = list1.toArray(new String[list1.size()]);
Arrays.sort(arrayOne);
//System.out.println(Arrays.toString(arrayOne));
int size = arrayOne.length;
double[] finalArray = new double[size];
for (int j = 0; j < size; j++) {
String word = arrayOne[j];
String newWord = word.substring(6, 10);
double grade = Double.parseDouble(newWord);
finalArray[j] = grade;
}return finalArray;
}
//ID's and second set of grades
private Scanner b;
public double[] openFile2() {
ArrayList<String> list2 = new ArrayList<String>(7);
try {
b = new Scanner(new File("IR102.txt"));
} catch (Exception e) {
System.out.println("could not find file");
}
while (b.hasNextLine()) {
list2.add(b.nextLine());
}
String[] arrayTwo = list2.toArray(new String[list2.size()]);
Arrays.sort(arrayTwo);
//System.out.println(Arrays.toString(arrayTwo));
int size = arrayTwo.length;
double[] finalArray2 = new double[size];
for (int j = 0; j < size; j++) {
String word = arrayTwo[j];
String newWord = word.substring(6, 10);
double grade2 = Double.parseDouble(newWord);
finalArray2[j] = grade2;
}return finalArray2;
}
// ID's and names
private Scanner c;
public void openFile3() {
ArrayList<String> list3 = new ArrayList<String>(7);
try {
c = new Scanner(new File("IRStudents.txt"));
} catch (Exception e) {
System.out.println("could not find file");
}
while (c.hasNextLine()) {
list3.add(c.nextLine());
}
String[] arrayThree = list3.toArray(new String[list3.size()]);
Arrays.sort(arrayThree);
//System.out.println(Arrays.toString(arrayThree));
int size = arrayThree.length;
String[] names = new String[size];
for (int j = 0; j < size; j++) {
names[j] = arrayThree[j].substring(6);
}
String[] IDs = new String[size];
for (int x = 0; x < size; x++){
IDs[x] = arrayThree[x].substring(0,5);
}
System.out.println(Arrays.toString(names));
System.out.println(Arrays.toString(IDs));
}
public void calculateAvg() {
}
}
I am trying to access the numbers in finalArray and finalArray2 but I am not sure how to do this when I try to call on the two arrays it does not work I think it is to do with the scope of the arrays.So how do I make the two array accessible to the whole program.
If you want to make the two arrays accessible to the whole program, declare them as static variables outside of the main method and initialize inside like seen here:
public class Marks {
static double[] finalArray;
static double[] finalArray2;
public static void main(String[] args) {
Marks r = new Marks();
finalArray = r.openFile();
finalArray2 = r.openFile2();
While you could make the arrays visible to the whole class, it probably makes more sense to pass them to the method which should access them. So do something like this:
public void calculateAvg(double[] array1, double[] array2) {
// ...
}
You can then call it like this:
public static void main(String[] args) {
Marks r = new Marks();
double[] finalArray = r.openFile();
double[] finalArray2 = r.openFile2();
r.calculateAvg(finalArray, finalArray2);
}

average method arrays hint

Can you give me a hint on what I'm doing wrong with my average in the average method? I'm trying to call the method in the read scores.I'm trying to get the average of the scores I have in my input.txt file.
import java.io.*;
import java.util.*;
public class FindGrade {
public static final int NUM_SCORE_TYPES = 5;
public static void main(String[] args) {
Scanner scan = null;
int[] quizArray = null;
int[] labArray = null;
int[] attendance = null;
int[] midterms = null;
int quizgrade =0;
int labgrade=0;
int attendance_1=0;
int midterms_1 =0;
String name;
try {
scan = new Scanner(new File("input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
// each iteration is for single exam type (ie: Quizzes is the 1st one)
for (int i = 0; i < NUM_SCORE_TYPES; i++) {
name = scan.next();
int numScores = scan.nextInt();
int maxGrade = scan.nextInt();
if (name.equals("Quizzes")) {
quizArray = new int[numScores];
readScores(quizArray, numScores, scan);
}
else if (name.equals("Labs")) {
labArray = new int[numScores];
readScores(labArray, numScores, scan);
}
else if (name.equals("Lab_attendance")) {
attendance = new int[numScores];
readScores(attendance, numScores, scan);
}
else if (name.equals("Midterms")) {
midterms = new int[numScores];
readScores(midterms, numScores, scan);
}
}
}
public static void readScores(int[] scoreArray, int numScores, Scanner scan) {
for (int i = 0; i < numScores; i++) {
scoreArray[i] = scan.nextInt();
}
}
public static void average(double [] scoreArray, int numScores){
double sum=0;
for(int i=0; i< scoreArray.length; i++){
sum += scoreArray[i];
}
double average = sum/numScores;
System.out.println(sum + " " + average);
}
In any case, you can't directly call it with the arrays that you are creating there. Because the arrays are of type int, but the average-method requires a double array. When you change this, you can call the method like this...
public static void readScores(int[] scoreArray, int numScores, Scanner scan) {
for (int i = 0; i < numScores; i++) {
scoreArray[i] = scan.nextInt();
}
average(scoreArray, numScores); // <----- Call it here
}
public static void average(int[] scoreArray, int numScores){
double sum=0;
for(int i=0; i< scoreArray.length; i++){
sum += scoreArray[i];
}
double average = sum/numScores;
System.out.println(sum + " " + average);
}

Forked Java VM exited abnormally. JUnit Test?

I have a simple Java program that seems to work well until uploaded to my school's grading system, "WebCat", which I'm assuming is just running JUnit. The error it kicks back is:
Forked Java VM exited abnormally. Please note the time in the report does not reflect the >time until the VM exit.
I've researched this issue and and the main first troubleshooting step seems to be to look at the dump log. Unfortunately I cannot do that in this case. I am really at a loss on how to begin to troubleshoot this considering the lack of feedback from the grading system and the lack of compile or run-time errors.
Here is the code if anyone is familiar with this error or can at least give me some direction of where to begin troubleshooting. Much appreciated!
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.io.IOException;
class PlayerApp {
public static void showMenu()
{
System.out.println("Player App Menu");
System.out.println("P - Print Report");
System.out.println("A - Add Score");
System.out.println("D - Delete Score");
System.out.println("L - Find Lowest Score");
System.out.println("H - Find Highest Score");
System.out.println("Q - Quit");
}
public static void main(String[] args) throws IOException
{
if (args.length == 0)
{
System.out.println("File name was expected as a run argument.");
System.out.println("Program ending.");
System.exit(0);
}
String fileName = args[0];
Scanner sc = new Scanner(System.in);
String stnew = "";
boolean exit = false;
Player p = null;
double[] scoreList;
File dbFile = new File(fileName);
FileInputStream fis = new FileInputStream(fileName);
InputStreamReader inStream = new InputStreamReader(fis);
BufferedReader stdin = new BufferedReader(inStream);
String name = stdin.readLine();
stnew = stdin.readLine();
int numScore = Integer.parseInt(stnew);
scoreList = new double[numScore];
for (int i = 0; i < numScore; i++)
{
stnew = stdin.readLine();
scoreList[i] = Double.parseDouble(stnew);
}
p = new Player(name, numScore, scoreList);
stdin.close();
System.out.println("File read in and Player object created.");
showMenu();
while (exit == false)
{
System.out.print("\nEnter Code [P, A, D, L, H, or Q]:");
String choice = sc.nextLine().toLowerCase();
if (choice.equals("p"))
{
System.out.println(p.toString());
}
else if (choice.equals("a"))
{
System.out.print(" Score to add: ");
stnew = sc.nextLine();
double scoreIn = Double.parseDouble(stnew);
p.addScore(scoreIn);
}
else if (choice.equals("d"))
{
System.out.print(" Score to delete: ");
stnew = sc.nextLine();
double scoreIn = Double.parseDouble(stnew);
p.deleteScore(scoreIn);
System.out.println(" Score removed.");
}
else if (choice.equals("l"))
{
System.out.println(" Lowest score: " + p.findLowestScore());
}
else if (choice.equals("h"))
{
System.out.println(" Highest score: " + p.findHighestScore());
}
else if (choice.equals("q"))
{
exit = true;
}
}
}
}
break
import java.text.DecimalFormat;
public class Player {
//Variables
private String name;
private int numOfScores;
private double[] scores = new double[numOfScores];
//Constructor
public Player(String nameIn, int numOfScoresIn, double[] scoresIn) {
name = nameIn;
numOfScores = numOfScoresIn;
scores = scoresIn;
}
//Methods
public String getName() {
return name;
}
public double[] getScores() {
return scores;
}
public int getNumScores() {
return numOfScores;
}
public String toString() {
String res = "";
DecimalFormat twoDForm = new DecimalFormat("#,###.0#");
DecimalFormat twoEForm = new DecimalFormat("0.0");
res += " Player Name: " + name + "\n Scores: ";
for (int i = 0; i < numOfScores; i++)
{
res += twoDForm.format(scores[i]) + " ";
}
res += "\n Average Score: ";
res += twoEForm.format(this.computeAvgScore());
return res;
}
public void addScore(double scoreIn) {
double newScores[] = new double[numOfScores +1 ];
for (int i = 0; i < numOfScores; i++)
{
newScores[i] = scores[i];
}
scores = new double[numOfScores + 1];
for(int i = 0; i < numOfScores; i++)
{
scores[i] = newScores[i];
}
scores[numOfScores] = scoreIn;
numOfScores++;
}
public boolean deleteScore(double scoreIn) {
boolean found = false;
int index = 0;
for (int i = 0; i < numOfScores; i++)
{
if (scores[i] == scoreIn)
{
found = true;
index = i;
}
}
if (found == true)
{
double newScores[] = new double[numOfScores -1 ];
for (int i = 0; i < index; i++)
{
newScores[i] = scores[i];
}
for (int i = index + 1; i < numOfScores; i++)
{
newScores[i - 1] = scores[i];
}
scores = new double[numOfScores - 1];
numOfScores--;
for (int i = 0; i < numOfScores; i++)
{
scores[i] = newScores[i];
}
return true;
}
else
{
return false;
}
}
public void increaseScoresCapacity()
{
scores = new double[numOfScores + 1];
numOfScores++;
}
public double findLowestScore() {
double res = 100.0;
for (int i = 0; i < numOfScores; i++)
{
if (scores[i] < res)
{
res = scores[i];
}
}
return res;
}
public double findHighestScore() {
double res = 0.0;
for (int i = 0; i < numOfScores; i++)
{
if (scores[i] > res)
{
res = scores[i];
}
}
return res;
}
public double computeAvgScore() {
double res = 0.0;
if (numOfScores > 0) {
for (int i = 0; i < numOfScores; i++)
{
res += scores[i];
}
return res / (double)(numOfScores);
}
else {
//res = 0.0;
return res;
}
}
}
Your program is calling System.exit(0) for certain inputs. Don't do that! That's exactly what the message is telling you: that the JVM exited in the middle of the text, before the scoring code could finish up. Instead of calling exit(), just use return to return from main() early.
The library System Rules has a JUnit rule called ExpectedSystemExit. With this rule you are able to test code, that calls System.exit(...).

Categories

Resources