-4

I have the following code to split a String of a list of words separated by spaces. The string is split and used to populate the array. If I use the .length method, will it return the amount of split strings? As in, would it be similar to the String.length method that counts the amount of characters and returns that value?

I want to have the program increment the array position by one each time it's run, but I want it to reset to 0 if it already used the last word, so it circles back and starts with the first word again.

Would this bit of code reset the word position to 0 when it has already used the last word in the array?

String wordsList[] = words.split(" ");
        this.currentWord = wordsList[wordPos];
        if(wordPos < wordsList.length)
            wordPos++;
        else
            wordPos = 0;
Joshua Dannemann
  • 2,003
  • 1
  • 14
  • 34
Johnson Gale
  • 155
  • 1
  • 11
  • [This addresses the question on if `.length` would give you back the total number of split entities...](http://stackoverflow.com/q/23730092/1079354) (yes, it does), but I'm confused at your second part. What do you mean by "reset the word position" on each run? Are you running this code in some kind of loop? – Makoto Oct 30 '15 at 22:00
  • If you want to know if your code works, why not compile and run it to find out? – Bethany Louise Oct 31 '15 at 00:08

2 Answers2

0

If you use array.length on an array doesn't it tell you what the length is? The answer is yes. Also, the .length is a property and not a method.
Take a look at this going over the .length property with a bit more detail. Cheers.

Community
  • 1
  • 1
Ceelos
  • 1,116
  • 2
  • 14
  • 35
0

If I understand correctly, It sounds like you want to use a for loop like this?:

String words = "Blah blarg bloob"
String wordsList[] = words.split(" ");
String currentWord = "";
for (int i = 0; i < wordsList.length; i++){
    if (currentWord !=null && currentWord.equals(wordsList[i])) {i = 0;}
    currentWord = wordsList[i];
}
  • 2
    You should use [equals to compare strings](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). BTW, you haven't initialized `currentword` – sam Oct 30 '15 at 22:21