【发布时间】:2016-06-19 00:54:27
【问题描述】:
我很难弄清楚为什么只有部分代码在工作。我从一个 txt 文件中提取数据,以提供回答用户提示回答问题的数据。这是我的错误:
线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:TestTitanic.filler(TestTitanic.java:13) 的 TestTitanic.main(TestTitanic.java:41) 中的 0
C:\Users\Jznica Sabatini\AppData\Local\NetBeans\Cache\8.1\executor-sn-ps\run.xml:53:
Java 返回:1 BUILD FAILED(总时间:0 秒)
这是第 13、41 行,我输入的是第 53 行,尽管我不确定那个错误是什么。
line 13 String content = new Scanner(new File(args[0]))
line 41 runner.filler(args);
所以我有一个测试类(上面的例子来自于一个 Titanic 类,虽然可能没有必要,但它是一个带有 extends 方法的 Titanic 的子类,但它全部编译了,只是当我在cmd 行,测试类以 titanic.txt 文件作为 cmd ln args 运行,当用户提示响应时,仅打印 7 个问题中的 3 个。
以下是我的TestTitanic 课程。我正在使用 netbeans 并允许通过建议进行更改,现在我什至没有让我的 cmd ln 打印问题或提示用户输入他们的响应。在 net beans 中,它说我的测试类是我的错误所在,但考虑到我的 cmd 行中一些错误行的数量,我知道这是我原来的 Titanic 父类,但现在我将从较小的错误开始。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TestTitanic {
// Method that builds a 2D array from the txt file
public void filler(String[] args) {
// Try-catch is needed for passing args to method
try {
// Turns the txt file into one large string
String content = new Scanner(new File(args[0]));
.useDelimiter("\\Z") // To the end of the file
.next();
String[] rows = content.split("\n"); // Breaks up by new line
// Creates a 2D array as "long" as the input file
String[][] titanic = new String[rows.length][];
// Fills the 2D array
for (int i = 0; i < rows.length; i++) {
titanic[i] = rows[i].split("\\t");
}
// Creates a new Titanic object
Titanic titanicObject = new Titanic(titanic);
// Calls the passToMenu method from Titanic class
titanicObject.passToMenu();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
public static void main(String[] args) {
// Create an object from this class
TestTitanic runner = new TestTitanic();
// Calls the program method to fill the array
Runnable runnable = new Runnable() {
@Override
public void run() {
runner.filler(args);
}
};
}
}
【问题讨论】:
-
第 13 行末尾没有分号!另外,请用
和附上您的代码行。 -
您为什么要在主线程中创建一个新线程?您似乎不打算使用多线程。另外:“...我正在使用 netbeans 并允许通过建议进行更改”
-
所以我修复了它并回到原来的问题,即输入我对问题的回答并根据我选择回答的问题接收多个越界错误。
线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 1 at Titanic.perishedPercent(Titanic.java:40) //line 40 if (row[1].equals("0")) {这只是其中一个错误的众多示例之一,但如果您想了解更多信息,我将非常乐意提供它以便更好地理解。 -
您上面提供的代码似乎没有我能发现的任何重大问题。现在您似乎在谈论代码的不同部分?
-
到
getCodeFormattingLikeThis();使用“`”字符,带有“~”的按钮就可以了。对于多行代码,突出显示代码并单击“{}”按钮或在该部分上制表符,每行八个空格。 (多行代码在 cmets 中不起作用)
标签: java multidimensional-array indexoutofboundsexception filereader