【问题标题】:Java returns woesJava返回困境
【发布时间】: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的结果?

标签: java arrays search


【解决方案1】:

这是解决方案,如果找到索引则返回其编号,否则在检查整个数组后返回-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;
}

【讨论】:

  • 感谢您的成功!我也明白为什么会这样
【解决方案2】:

现在你有了它,所以当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;
}

【讨论】:

  • OP 在返回之前也会打印出来。
【解决方案3】:

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

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;
}

【讨论】:

  • 第二种方法是区分大小写的,因此不起作用。
  • 然后改正它,否则会有一些反对者(不是我;)。
猜你喜欢
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-02
  • 2013-04-23
相关资源
最近更新 更多