需要帮助修复while循环

时间:2015-09-13 09:42:08

标签: java string while-loop int

您好我正在尝试创建一个模拟数据库搜索,虽然它可以工作,每当我输入一个不属于数据库的输入时,它会在线程“main”中创建一个Exception java.lang.ArrayIndexOutOfBoundsException:4 on line 23.我不知道还能做什么,因为我发现代码中没有错误。

import java.util.*;

public class Database {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner scan = new Scanner(System.in);
    String[] names = new String[4];

    boolean found = false;
    int i = 0;
    names[0] = "Thor";
    names[1] = "Ben";
    names[2] = "Zoe";
    names[3] = "Kate";

    System.out.println("Enter Player Name");
    String input = scan.nextLine();

    while(found != true){

        if(input.equals(names[i])){
            System.out.println(input + " has been found");
            found = true;
        } else {
            i = i+1;
        }
        if(i == 3 && found == false){
            System.out.println(input + " was not found");
        }

      }

    }

  }

3 个答案:

答案 0 :(得分:1)

打印input + " was not found"后,您不会离开循环。 因此,循环的下一次迭代抛出ArrayIndexOutOfBoundsException

在完成整个阵列的测试后,你应该离开循环。

变化

    while(found != true){

    while(!found && i < names.length){

实际上你可以移动if语句来测试输入是否在循环之后:

  while(!found && i < names.length) {
    if(input.equals(names[i])){
        System.out.println(input + " has been found");
        found = true;
    } else {
        i = i+1;
    }
  }
  if(!found){
      System.out.println(input + " was not found");
  }

更好的选择是使用for循环:

  for (int i = 0; i < names.length && !found; i++) {
    if(input.equals(names[i])){
        System.out.println(input + " has been found");
        found = true;
    }
  }
  if(!found){
      System.out.println(input + " was not found");
  }

答案 1 :(得分:0)

如果你的输入不匹配,i的值将继续递增,你的数组长度为4.显然是ArrayindexoutofException。 为了避免你需要考虑数组长度。

答案 2 :(得分:0)

您只需更改为

即可
while(i < names.length)

并忘记了额外的布尔变量。由于您希望在找到解决方案之前继续迭代i,因此停止条件将是最大值i。当您找到解决方案时,您只需break while语句:

if (input.equals(names[i])) {
    System.out.println(input + " has been found");
    break;
}