Oluwatosin Edwards Oluwatosin Edwards - 4 years ago 108
Java Question

Java returns woes

Okay so I have the following code and no matter what it returns to me a -1. I want to have it so that if the id matches then it returns and index but if it doesn't match after running through the whole data set it returns a negative one. Where am I going wrong here:

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

Answer Source

Here is the solution where if index is found then its number is returned, else if it isn't after checking whole array, -1 is returned and appropriate Strings are printed.

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

You can also use 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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download