What's wrong with my program - error message but works fine?

108 Views Asked by At

My program runs exactly the way I want it to, but I get an error message in the console:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size: 6

at java.util.ArrayList.rangeCheck(ArrayList.java:653)

at java.util.ArrayList.get(ArrayList.java:429)

at Kevinmath4.checkAnswers(Kevinmath4.java:152)

at Kevinmath4.main(Kevinmath4.java:39)

Here is the code:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Scanner;

import javax.swing.JOptionPane;

public class Kevinmath4 {
    static File filename = new File("homework.txt");
    static ArrayList<Object> aList = new ArrayList<Object>();
    static String homework = "";
    static File filename2 = new File("homework2.txt");
    static ArrayList<Object> aList2 = new ArrayList<Object>();
    static String homework2 = "";
    static String answerPass = "";
    static ArrayList<Object> aList3 = new ArrayList<Object>();
    static final int TOTAL_QUESTIONS = 5;
    static String date;

    public static void main(String[] args) throws FileNotFoundException {
        String initialInput = JOptionPane.showInputDialog(null,
                "Enter Add answers / Check answers to continue");

        switch (initialInput) {
        case "Add answers":
            answers("excalibur117", aList, filename);
            break;

        // Need to store the array permanently
        case "Check answers": // Need to make it so it stores array of
            // Kevin's answers permanently
            clearFile(filename2);
            answers("Kevin", aList2, filename2);
            readAnswers(filename, aList3);
            checkAnswers(aList3, aList2);
            break;

        default:
            JOptionPane.showMessageDialog(null, "Please enter a valid option.");
            break;
        }
        clearFile(filename2);

        // exit the program
        JOptionPane.showMessageDialog(null,
                "Thanks for using this program. Cheers!");
    }

    public static void answers(String pass, ArrayList<Object> list, File f) {

        answerPass = JOptionPane.showInputDialog(null,
                "Please enter the password");
        // validate user
        while (!answerPass.equals(pass)) {
            JOptionPane.showMessageDialog(null,
                    "Incorrect Password. Please try again.");
            answerPass = JOptionPane.showInputDialog(null,
                    "Please enter the password.");
        }

        // add answers
        String final1 = "";
        do {
            list.clear();

            // validate the date of the answers
            date = JOptionPane.showInputDialog(null,
                    "Enter the date of the desired" + " answers (MM/DD/YY)");
            // add your answers
            enterAnswers(date, list, f);

            // verify the answers
            final1 = JOptionPane.showInputDialog(null, "Is this correct: "
                    + list.get(1) + " " + list.get(2) + " " + list.get(3) + " "
                    + list.get(4) + " " + list.get(5) + "? (Yes/No)");

        } while (final1.charAt(0) == 'n' || final1.charAt(0) == 'N');
    }

    public static void enterAnswers(String options, ArrayList<Object> list,
            File f) {

        do {
            boolean valid = false;
            list.add(date);
            for (int i = 0; i < 5; i++) {
                while (!valid) {
                    homework = JOptionPane
                            .showInputDialog("Please enter your answer for question "
                                    + (i + 1));
                    if (!homework.isEmpty())
                        valid = true;
                }
                list.add(homework);
                valid = false;
            }

            writeFile(f, list); // write the answers to a file

            break;

        } while (!homework.isEmpty());
    }

    public static void writeFile(File filename, ArrayList<Object> list) {
        try {
            FileWriter fw = new FileWriter(filename, true);
            Writer output = new BufferedWriter(fw);

            for (int j = 0; j < list.size(); j++) {
                output.write(list.get(j) + "\n");
            }
            output.close();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,
                    "Oops! I cannot create that file.");
        }
    }

    public static void clearFile(File filename) {
        try {
            FileWriter fw = new FileWriter(filename, false);
            Writer output = new BufferedWriter(fw);
            output.write("");
            output.close();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,
                    "Oops! I cannot create that file.");
        }
    }

    public static void checkAnswers(ArrayList<Object> a, ArrayList<Object> b) {
        int i = 1; // counter variable
        int j = a.indexOf(date);
        for (Object obj : a) { // iterate through any list
            for (int k = (j + 1); k < (j + 6); k++) {
                if (obj.getClass() == String.class) { // find if it's a
                    // string
                    if (!a.get(k).equals(b.get(i))) {
                        JOptionPane.showMessageDialog(null, "#" + (i)
                                + " is wrong.");
                    }
                }

                if (obj.getClass() == Double.class) { // or a double
                    if (!a.get(k).equals(b.get(i))) {
                        JOptionPane.showMessageDialog(null, "#" + (i)
                                + " is wrong.");
                    }
                }

                if (obj.getClass() == Integer.class) { // or an integer
                    if (!a.get(k).equals(b.get(i))) {
                        JOptionPane.showMessageDialog(null, "#" + (i)
                                + " is wrong.");
                    }
                }
                i++;

            }
        }
    }

    public static void readAnswers(File filename, ArrayList<Object> list)
            throws FileNotFoundException {
        Scanner s = new Scanner(new File("homework.txt"));
        while (s.hasNextLine()) {
            list.add(s.nextLine());
        }
        s.close();
    }
}

What am I doing wrong?

2

There are 2 best solutions below

0
On

The problem is your for loop here,

for (int k = (j + 1); k < (j + 6); k++) {

when you then (blindly) access a.get(k) you don't know that k < a.size() (if it's == a.size() you'll get your posted exception). I think you wanted,

for (int k = (j + 1); k < a.size(); k++) {
0
On

Generically speaking, situations that sound like "My code does what it is supposed to, but then I get an Exception anyway", particularly in academic work, usually means that you've iterated a loop one too many times. This is reinforced by the type of exception, an ArrayIndexOutOfBoundsException.

Consider the array {a, b, c}. By now, I'm sure you know that the value at position 0 of said array is 'a', position 1 contains 'b', and position 2 contains 'c'. If you attempt, in Java, to access position 3 of this array, you will get an ArrayIndexOutOfBoundsException, because there is no element at position 3, and the array isn't that long.

I'm going to go out on a limb and guess that line 152 is this one: if (!a.get(k).equals(b.get(i)))

I'm going to guess that a.get(k) is getting called when k == 6, but a is only length 6 (which means its highest index is 5).

I'm going to guess that the expression for (int k = (j + 1); k < (j + 6); k++) is the culprit, and I'm going to guess that the expression should be for (int k = (j + 1); k < (j + 5); k++)

I can only guess, however, because, frankly (and not trying to be rude...just saying...), your code is a mess. Better variable names, comments, and less use of magic numbers will take you far.

Hope this helps.