从Questions / Answers文件返回字符串

时间:2013-12-22 21:16:34

标签: java indexoutofboundsexception

我正在编写一个使用Wolfram Alpha API的搜索Java程序。它将问题存储在一个文本文件中,将Answers存储在另一个文本文件中。我正在尝试合并一个功能,告诉用户以前是否询问过这个问题&为用户提供已保存的答案(而不是搜索Wolfram Alpha)。

Questions.listAnswers.list都将输入/输出存储在相同的相应行上。我正在使用以下代码输出结果:

ArrayList<Question> searchArray = prevQuest(userInput);
int index = searchList(searchArray, userInput);

if(index >=0){ //tells program which arraylist to search and the string to search for.
  System.out.println("This question has already been asked. The previous answer was:");
  previousAnswers.get(index).print();
  askQuestion(); // runs method again to avoid doing a WAlpha Search.

我也在使用这种方法:

public static int searchList(ArrayList<Question> list, String userInput){
  int j =-1;


  for(int i=0; i<list.size()-1; i++) {
    if(list.get(i).getQuestion().substring(0, list.get(i).getQuestion().length()).equalsIgnoreCase(userInput)){
      j=i;
    }

  return j-1;

它返回所提问题的错误存档答案 - 例如如果我之前问过谁发明了这辆车 - 它会说“这个Q已经被问过了。之前的答案是:Kurt Cobain。我可能在前一个问题中问过这个问题。如果我将return J-1更改为{{ 1}}。它给了我一个return J

IndexOutOfBoundsException

有谁知道我可能做错了什么?或者更好的方法呢?

非常感谢任何帮助。

感谢。

1 个答案:

答案 0 :(得分:1)

您的问题列表和答案列表实际上必须有不同的长度,或者searchList有错误。您的searchList方法正在返回,索引为3匹配,但您的答案列表中只有3个项目。

此外,返回j是正确的,而j-1实际上会返回错误的索引。