【发布时间】:2016-03-12 10:34:12
【问题描述】:
您好,我想知道如何编写一个 try and catch 块来阻止出现以下错误。
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
我有这个方法,它接受一个句子并将其拆分为一个 ArrayList。然后我使用它将值存储到哈希图中,其中索引 1 是键,后面的单词成为值。我使用下面的方法将用户输入拆分成一个数组。
私人扫描仪阅读器;
/**
* Create a new InputReader that reads text from the text terminal.
*/
public InputReader()
{
reader = new Scanner(System.in);
}
public ArrayList<String> getInput()
{
System.out.print("> "); // print prompt
String inputLine = reader.nextLine().trim().toLowerCase();
String[] wordArray = inputLine.split(" "); // split at spaces
// add words from array into ArrayList
ArrayList<String> words = new ArrayList<String>();
for(String word : wordArray) {
words.add(word);
}
return words;
}
}
下面的方法使用上面的类来检测用户输入。因此,当用户输入 write 时,他们可以写入 hashmap,但是如果他们在输入键和值之前按回车键,我会得到越界异常。那么我该如何重写下面的方法来避免这种情况呢?
public void start()
{
boolean finished = false;
printWelcome();
while(!finished) {
ArrayList<String> input = reader.getInput();
if(input.contains("shutdown")) {
finished = true;
}
if (input.contains("load")) {
System.out.println();
instruct.readAndFill();
System.out.println();
}
if (input.contains("write")) {
String key = input.get(1);
String value = "";
for(int i=2; i<input.size(); i++) {
value = value + " " + input.get(i);
}
instruct.mapWrite(key, value);
}
}
instructorGoodBye();
}
对不起,如果我不够清楚,或者我的代码没有达到标准,我现在才学习 java 大约 2 个月。
【问题讨论】:
-
大小为 1 的容器(数组、列表等)只有一个元素,索引为零。尝试使用索引 1 会出现越界错误。请使用调试器(Eclipse、NetBeans、Idea)来单步调试您的代码并在出现异常时停止,这样您就可以看到发生了什么。如果您不知道如何执行此操作,请在网络上查找教程并在做任何其他事情之前学习。使用调试器是学习编码的基础,除非您这样做,否则您将受到严重限制。
-
您的问题可能出在这一行:
String key = input.get(1);,要成功,您的列表中需要包含两个元素,而且看起来只有一个。 -
@nickb HI Nick 基本上 if (input.contains("write")) 被视为第一个元素,基本上如果用户在一行上输入 write key value 就可以了,但如果他们点击写入后返回,然后发生错误。我不知道如何重写它以避免这种情况。
-
运行时异常如
IndexOutOfBoundsException或NullPointerException表示程序逻辑不正确。不要尝试使用try...catch修复它们。相反,更正程序,使其不提供错误的索引或无效的参数等。 -
@JimGarrison 感谢 Bluej 确实带有调试器,我现在会看看它。
标签: java hashmap indexoutofboundsexception bluej