So I have a method called indexOf and by specifying a string in main, I can make the program print out the index of that string within the array. But how would I go about simply having a method that can print out the first index of an array, without me needing to specify a string, at all? If the index does not exist, I want it to return -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;                                      
    }
}
有帮助吗?

解决方案

Your question can be read two ways. If you want to be able to return just the first index of the array, then do the following:

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

However, you may mean to ask to return the first case of a String s in the array v. Then in that case, do the following:

//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

You seem new to java. I highly recommend reading these two sources:

Java: Array with loop

How do I compare strings in Java?

其他提示

The first index of an array is always 0. So you would just return v.length > 0 ? 0 : -1.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top