我已经编写了一个名为getIndex的方法,当我运行测试仪时它不会返回数字。

public int getIndex(String s){
    int index = -1;
    for(int i = 0; (i < names.length && index == 1); i++)
    {
        if(names[i].equals(s)) {
            index = i;
        }
    }
    return index;
}


如果不清楚,我试图使该方法返回给定字符串位于数组中的哪个位置。

编辑 -
[这是我在ideone上的代码](http://ideone.com/CM9xID

最佳答案

您以错误的方式进行迭代,如果比较index == 1,则循环永远不会开始,因为使用-1声明了index。如果您将索引声明为1,则循环将开始,但如果names [1]不等于s则无限循环,因此只需将其删除即可。

public int getIndex(String s){
    for(int i = 0; (i < names.length; i++)
    {
        if(names[i].equals(s)) { //use equalsIgnoreCase if comparing should be case insensitive
            return i; //found
        }
    }
    return -1; //not found
}


进行循环的另一个版本是(如果只需要索引,可以直接使用indexOf(),如上一个示例所示):

List<String> names2 = new ArrayList<String>(Arrays.asList(names));
for(String name : names2){
    if(name.equals(s))
        return names2.indexOf(name);
}


这是loop的增强功能。

您还可以快捷方式直接获取索引:

 List<String> names2 = new ArrayList<String>(Arrays.asList(names));
 return names2.indexOf(s);


Ideone Fiddle

请注意,您始终只会获得第一次出现的索引。如果s在数组中不止一次,则必须对其进行增强以存储找到的索引并返回所有索引!

public List<Integer> getIndexes(String s){
    List<Integer> found = new ArrayList<Integer>();
    for(int i = 0; (i < names.length; i++)
    {
        if(names[i].equals(s)) { //use equalsIgnoreCase if comparing should be case insensitive
            found.add(i);
        }
    }
    return found;
}

关于java - 为什么我的getIndex方法不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25758085/

10-11 22:28
查看更多