-5

My friend sent me this piece of code and it works, but I can't understand what the "ss" means? Can anyone help me out? Thanks.

public static void main(String[] args)
{
    String sentence;
    int index=1;
    String[] words;

    System.out.print("Please enter a sentence: ");
    sentence = EasyIn.getString();

    words = sentence.split(" ");

    for(String ss : words )
    {
        System.out.println("Word "+index+ " is "+ ss);

        if(ss.matches("[a-zA-Z]+"))
        {
            System.out.println("Word "+ss+" is a good word");
            System.out.print("\n");
        }
        else
        {
            System.out.println("Word "+ss+" is a bad word");
            System.out.print("\n");
        }
        index++;
    }
}
Alan
  • 7,875
  • 1
  • 28
  • 48

4 Answers4

3

This is a loop

for(String ss : words )

and it says: for every element in words, create a temporary element (String) called ss. So it is saying, step through every element in words, call it ss for this single loop, do something with it then move on to the next.

Ross Drew
  • 8,163
  • 2
  • 41
  • 53
1

The ss variable used in the code is part of the for loop. ss represents each single string in the collection of words. You might want to consult the java language tutorial on the for loop workings.

DukeMe
  • 167
  • 2
  • 8
1

The code:

for(String ss : words) {
    // ...
}

is Java's for-each loop, which iterates over each element in the collection or array parameter. The String ss bit declares a variable named ss in the scope of the loop.

The requirement for the collection parameter is that it needs to be of a type that implements the Iterable<T> interface or an array.

Kallja
  • 5,362
  • 3
  • 23
  • 33
0

The variable ss is a local variable used an iterator. The are two types of for loops available in java. First: for(int i=0;i<5;i++){ //block of code } Second: for(int i:array) { //block of code }

The one you have mentioned is the second type of for loop.

ss acts as an iterator and iterates through each word formed as a result of splitting the input sentence based on the given regular expression which is " "(space) in your case.

yuvrajm
  • 316
  • 1
  • 3
  • 15