Reputation: 11
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;
}
Upvotes: 0
Views: 70
Reputation: 322
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;
}
Upvotes: 1
Reputation: 3749
i think you need something like this :
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;
}
Upvotes: 0
Reputation: 1382
Right now you have it so when ids[i].equalsIgnoreCase(id)
is true, it will set noIndex
to -1 (in the else statement) and break the for loop which will make it return -1. When that is false, it will print out the index.
Like everyone else has already posted, here is the code to find the index.
private int findIndex(String id) {
for (int i=0;i<ids.length;i++){
if(ids[i].equalsIgnoreCase(id)){
return i;
}
}
return -1;
}
Upvotes: 1