[英]Java returns woes
Okay so I have the following code and no matter what it returns to me a -1. 好的,所以我有以下代码,无论返回什么,我都为-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.
我想拥有它,以便如果id匹配则返回并索引,但如果在遍历整个数据集后不匹配,则返回负数。 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;
}
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. 这是一种解决方案,如果找到索引,则返回其编号,否则,如果在检查整个数组后未返回编号,则返回-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;
}
You can also use Java 8 Stream: 您还可以使用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;
}
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. 现在,您拥有了它,因此当
ids[i].equalsIgnoreCase(id)
为true时,它将noIndex
设置为-1(在else语句中)并中断for循环,这将使其返回-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;
}
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.