【发布时间】:2017-02-06 23:00:49
【问题描述】:
好的,所以我有以下代码,无论它返回给我一个 -1。我想拥有它,以便如果 id 匹配,则它返回并索引,但如果它在运行整个数据集后不匹配,则返回负数。我哪里错了:
public class StudentCollection {
private String[] ids = new String[] {"Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty"}; // keeps identification numbers of students
private String [] names = new String[] {"Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty"};; // keeps the names of students
private int size = 0; // number of students currently in the collection
private int findIndex(String id) {
int noIndex = 1;
for (int i=0;i<ids.length;i++){
if((ids[i].equalsIgnoreCase(id))){
System.out.println("The index of this student is " +i);
}
else {
noIndex = -1;
System.out.println(noIndex);
break;}
}
return noIndex;
}
【问题讨论】:
-
您的代码中的
ids是什么? -
提示:你在哪里设置 noIndex 为你想要返回的值?你应该什么时候休息?为什么要否定equalsIgnoreCase的结果?