Java回归困境

时间:2017-02-06 23:00:49

标签: java arrays search

好的,所以我有以下代码,无论它返回给我一个-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;
}

3 个答案:

答案 0 :(得分:1)

这是一个解决方案,其中如果找到index然后返回它的数字,否则如果它不是在检查整个数组之后,返回-1并且打印适当的字符串。

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);
          return i;
       }
    }
    System.out.println(noIndex);
    return noIndex;
}

您也可以使用Java 8 Stream:

private int findIndex(String id) {
    OptionalInt index = IntStream.rangeClosed(0, ids.length-1)
                                 .filter(i -> ids[i].equalsIgnoreCase(id))
                                 .findFirst();
    if(index.isPresent()) {
        int i = index.getAsInt();
        System.out.println("The index of this student is " + i);
        return i;
    }
    System.out.println(-1);
    return -1;
}

答案 1 :(得分:1)

现在你有了它,所以当ids[i].equalsIgnoreCase(id)为真时,它会将noIndex设置为-1(在else语句中)并打破for循环,这将使它返回-1。当这是错误时,它将打印出索引。 像其他人已经发布的一样,这里是找到索引的代码。

private int findIndex(String id) {
    for (int i=0;i<ids.length;i++){
        if(ids[i].equalsIgnoreCase(id)){
            return i;
        } 
    }

    return -1;
}

答案 2 :(得分:0)

我认为你需要这样的东西:

private int findIndex(String id) {

    for (int i=0; i<ids.length; i++){

        if(ids[i].equalsIgnoreCase(id)){

            System.out.println("The index of this student is " +i);

            return i;   
        }
    }

    return -1;
}