Java 需要帮助修复while循环吗
嗨,我试图创建一个模拟数据库搜索,尽管它可以工作,但每当我输入一个不属于数据库的输入时,它就会在线程“main”java.lang.ArrayIndexOutOfBoundsException:4的第23行中创建一个异常。我不知道还能做什么,因为我看不到代码中有错误Java 需要帮助修复while循环吗,java,string,while-loop,int,Java,String,While Loop,Int,嗨,我试图创建一个模拟数据库搜索,尽管它可以工作,但每当我输入一个不属于数据库的输入时,它就会在线程“main”java.lang.ArrayIndexOutOfBoundsException:4的第23行中创建一个异常。我不知道还能做什么,因为我看不到代码中有错误 import java.util.*; public class Database { public static void main(String[] args) { // TODO Auto-generated me
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");
}
}
}
}
打印未找到的
input+”后,您不会离开循环“
。
因此,循环的下一次迭代将抛出ArrayIndexOutOfBoundsException
您应该在完成整个阵列的测试后离开循环
改变
while(found != true){
到
while(!found&&i
实际上,您可以移动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");
}
while(!found&&i
更好的选择是使用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");
}
for(int i=0;i
将while循环更改为
while (found != true) {
if (input.equals(names[i])) {
System.out.println(input + " has been found");
found = true;
} else {
i = i + 1;
}
if (i == 4 && found == false) { //changed here
System.out.println(input + " was not found");
//or found == true;
break; //and here
}
}
如果此条件为真,则需要退出循环
i == 4 && found == false
要真正退出,你必须“打破”while条件
found != true
您可以通过设置found=true
(但这在语义上不正确)或添加break
指令来完成此操作
以下是while循环的替代解决方案:
while (!found && i<4)
if (input.equals(names[i++]))found = true;
System.out.println(input+(found?" has been":" was not")+" found");
while(!found&&i如果您的输入与i的值不匹配,我将继续递增,并且您的数组长度为4。显然,ArrayindexoutofException。
为了避免你也需要考虑数组长度。 你可以简单地更改为
while(i < names.length)
顺便说一句,你可以做i++
(而不是i=i+1
)和!found
(而不是found==false
);谢谢!它非常有效。我将在我的完整数据库中记住它。这是一个测试所需概念的实践。
while(i < names.length)
if (input.equals(names[i])) {
System.out.println(input + " has been found");
break;
}