返回给定数组的第一个索引

时间:2014-01-27 15:44:14

标签: java arrays indexof

所以我有一个名为indexOf的方法,通过在main中指定一个字符串,我可以让程序打印出该数组中该字符串的索引。但是,我如何才能简单地拥有一个可以打印出数组的第一个索引的方法,而根本不需要指定字符串?如果索引不存在,我希望它返回-1。

public static void main(String[] args)
{

    String[] v = new String[1];
    v[0] = "test";

    String s = "t";

    indexOf(v, s);
}

public static int indexOf(String[] v, String s)
{       
    int i = v[0].indexOf(s);
    System.out.println
        ("Index of the first string in the first array: " + i);

    return -1;                                      
    }
}

2 个答案:

答案 0 :(得分:0)

数组的第一个索引始终为0.所以你只需return v.length > 0 ? 0 : -1

答案 1 :(得分:0)

您的问题可以通过两种方式阅读。如果您希望只能返回数组的第一个索引,请执行以下操作:

if(v.length > 0)//check length
    return 0;//return first position
return -1;//return empty string meaning there wasnt a first position.

但是,您可能要求在数组s中返回字符串v的第一个案例。然后在这种情况下,执行以下操作:

//assuming v and s are not null or do not contain null values
for(int i = 0; i < v.length; i++){//loop through the array v
    if(v[i].equals(s){//does the current value of v equal to the String s?
        return i;//found string!
    }
}
return -1;//didnt find the string

你似乎对java不熟悉。我强烈建议您阅读这两个来源:

Java: Array with loop

How do I compare strings in Java?

相关问题