【问题标题】:What's wrong with my program - error message but works fine?我的程序有什么问题 - 错误消息但工作正常?
【发布时间】:2015-06-10 00:09:25
【问题描述】:

我的程序完全按照我想要的方式运行,但我在控制台中收到一条错误消息:

线程“主”java.lang.IndexOutOfBoundsException 中的异常:索引: 6、尺寸:6

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

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

在 Kevinmath4.checkAnswers(Kevinmath4.java:152)

在 Kevinmath4.main(Kevinmath4.java:39)

代码如下:

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();
    }
}

我做错了什么?

【问题讨论】:

  • 请问第 152 行是哪一行代码?
  • 你认为异常意味着什么?

标签: java arraylist


【解决方案1】:

问题是你的for 循环在这里,

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

当您随后(盲目地)访问a.get(k) 时,您不知道 k &lt; a.size()(如果是== a.size(),您将收到您发布的异常)。我想你想要,

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

【讨论】:

    【解决方案2】:

    一般来说,听起来像“我的代码完成了它应该做的事情,但是我还是得到了一个异常”的情况,特别是在学术工作中,通常意味着你已经迭代了一个循环太多次。异常类型ArrayIndexOutOfBoundsException 强化了这一点。

    考虑数组 {a, b, c}。到现在为止,我确定您知道该数组的位置 0 处的值为“a”,位置 1 包含“b”,位置 2 包含“c”。如果你在 Java 中尝试访问这个数组的位置 3,你会得到一个 ArrayIndexOutOfBoundsException,因为位置 3 没有元素,而且数组没有那么长。

    我打算出去猜猜第 152 行是这一行: if (!a.get(k).equals(b.get(i)))

    我猜 a.get(k) 在 k == 6 时被调用,但 a 的长度仅为 6(这意味着它的最高索引为 5)。

    我猜for (int k = (j + 1); k &lt; (j + 6); k++)这个表达式是罪魁祸首,我猜这个表达式应该是for (int k = (j + 1); k &lt; (j + 5); k++)

    但是,我只能猜测,因为坦率地说(而不是试图粗鲁......只是说......),你的代码是一团糟。更好的变量名、cmets 和更少的幻数使用会让你走得更远。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-31
      • 2023-04-06
      • 2014-09-15
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 2019-08-15
      • 2016-04-18
      相关资源
      最近更新 更多