Search code examples
javaarraysfileindexoutofboundsexception

Array Index Out Of Bounds Java


I have an array thats supposed to be a size of 3 which takes in 3 dive totals. It takes in an array of 7 scores from a double []. I have used a test scenario to see if the diveScore() method works and the calculations are correct. But when i try to read the numbers from a file and put them into an array, the scoreArray that holds the calculated dive score for each dive fails to store the data. The scoreArray in my hard coded test case works fine. Here is the exception from the console when run. I have tried to look at the line where the error states but the test data that I commented out in the main file works fine with the 3 arrays of scores for each dive. What am I missing? Every for loop doesn't have <= in it like many articles have been shown to me by everyone.

Exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 
Index 3 out of bounds for length 3
    at Diver.diveScore(Diver.java:33)
    at Main.readFile(Main.java:74)
    at Main.main(Main.java:10)

Main File:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) throws FileNotFoundException {
        Diver [] divers = new Diver[25];
        
        int numDivers = readFile(divers);
        System.out.println(numDivers);
        /*Diver d = new Diver("Frank Stalteri", "Middlesex County College");
        double [] scores = {6.2, 3.5, 8, 7.3, 6, 9.1, 4.8};
        double [] scores2 = {7.4, 5.4, 8, 3.7, 2.5, 7.8, 4};
        double [] scores3 = {4.6, 7.2, 7.3, 1.4, 3.6, 8, 4.7};
        
        d.diveScore(1, scores, 2);
        d.diveScore(2, scores2, 4);
        d.diveScore(3, scores3, 3);
        
        System.out.println(d.toString());
        */
    }
    public static int readFile(Diver [] divers) throws FileNotFoundException {
        File f = new File("divers.dat");
        Scanner kb = new Scanner(f);
        Diver d;
        
        int count = 0;
        int diveNum = 1;
        
        while (kb.hasNextLine()) {
            String name = kb.nextLine();
            String school = kb.nextLine();
            String dive1 = kb.nextLine();
            String dive2 = kb.nextLine();
            String dive3 = kb.nextLine();
            
            //String [] of size 8 (inlcudes the difficulty #)
            String [] scores1 = dive1.split("\\s+");
            String [] scores2 = dive2.split("\\s+");
            String [] scores3 = dive3.split("\\s+");
            
            //gets the difficulty from String [] then parses
            double diff1 = Double.parseDouble(scores1[scores1.length - 1]);
            double diff2 = Double.parseDouble(scores2[scores2.length - 1]);
            double diff3 = Double.parseDouble(scores3[scores3.length - 1]);
            
            //make new double [] of size 7
            double [] scores1D = new double[scores1.length - 1];
            double [] scores2D = new double[scores2.length - 1];
            double [] scores3D = new double[scores3.length - 1];
            
            //loops through String [] and casts numbers without difficulty number
            for (int i = 0; i < scores1D.length; i++) {
                scores1D[i] = Double.parseDouble(scores1[i]);
                //System.out.println(scores1D[i]);
            }
            for (int i = 0; i < scores2D.length; i++) {
                scores2D[i] = Double.parseDouble(scores2[i]);
                //System.out.println(scores2D[i]);
            }
            for (int i = 0; i < scores3D.length; i++) {
                scores3D[i] = Double.parseDouble(scores3[i]);
                //System.out.println(scores3D[i]);
            }
            
            d = new Diver(name, school);
            divers[count] = d;
            count++;
            
            d.diveScore(diveNum, scores1D, diff1);
            diveNum++;
            d.diveScore(diveNum, scores2D, diff2);
            diveNum++;
            d.diveScore(diveNum, scores3D, diff3);
            
            //System.out.println(d.toString());
        }
        kb.close();
        return count;
    }
    public static void printDivers(Diver [] divers, int numDivers) {
        System.out.println("All Divers\n");
        for (int i = 0; i < divers.length; i++) {
            if (divers[i] != null) {
                System.out.println(divers[i]);
            }
        }
    }
}

Diver File:

public class Diver {
    
    private String name;
    private String school;
    private double [] scoreArray = new double [3];
    private double totalScore;

    Diver() {
        
    }
    Diver(String name, String school) {
        this.name = name;
        this.school = school;
    }
    //loop through score array and calculate the total score for each dive attempt
    public double [] diveScore(int diveNum, double [] scores, double difficulty) {
        double min = min(scores);
        double max = max(scores);
        double total = 0;
        
        for (int i = 0; i < scores.length; i++) {
            total += scores[i];
        }
        total -= max;
        total -= min;
        total *= difficulty;
        
        scoreArray[diveNum - 1] = Math.round(total * 100.0) / 100.0;
        return scoreArray;
    }
    //finds smallest score in array of scores
    private double min(double [] scores) {
        java.util.Arrays.parallelSort(scores);
        
        double min = scores[0];
        return min;
    }
    //finds largest score in array of scores
    private double max(double [] scores) {
        java.util.Arrays.parallelSort(scores);
        
        double max = scores[scores.length - 1];
        return max;
    }
    //calculates total of the 3 dives
    public double totalScore() {
        for (int i = 0; i < scoreArray.length; i++) {
                totalScore += scoreArray[i];
        }
        return totalScore;
    }
    public String toString() {
        String str = name + ", " + school + ": " + totalScore() + "\n" + "Dive 1: " + scoreArray[0] + "\n" + "Dive 2: " + scoreArray[1] + "\n" + "Dive 3: " + scoreArray[2] + "\n";
        return str;
    }
public boolean equals(Diver d) {
    boolean value = true;
        if (d == null || !(d instanceof Diver)) {
            value = false;
            return value;
        }
        Diver diver = (Diver) d;
        if (this.totalScore == d.totalScore) {
            value = true;
            return value;
        }
        return value;
    }
}

Solution

  • Your first diver must start at 0
    Main > readFile > while loop

    int diveNum = 0;