Indigo
Indigo

Reputation: 787

For loop is acting differently

Here is a little code

public static void isAscending(String[] array){
    // TODO This function will verify the details of the column if the column contents are actually ascending

    for(String a: array)
        log(a);
    Arrays.sort(array);
    for(String ao: array)
        log(ao);
}

In the above, if I just use the first for loop, I get all the elements in the order they were passed. If I put both of them together, I get no output. (Log is a function which does the same as System.out.println)

Am I making some major mistake? I cannot see the reason for the second loop to not work

LOG METHOD:

public static void log(String text) {
        System.out.println(text);
    }

INPUT ARRAY: I am taking the array from a webpage(using Selenium). Here is the function doing that (It works perfectly and gives the output I expect it to be) :

public static String[] getEmail() {
    WebElement table_element = driver.findElement(By.className(TABLE_RESPONSE));
    List<WebElement>    tr_collection=table_element.findElements(By.xpath("//tbody//tr[position()>2]"));
    int i=0;
    String[] emails = new String[tr_collection.size()];
    for(WebElement trElement : tr_collection) {
        WebElement email = trElement.findElement(By.className("email"));
        String email_id = email.getText();
        emails[i] = email_id;
        i++;
    }
    return emails;
}

Here is how I call it:

isAscending(getEmail());

Upvotes: 0

Views: 96

Answers (1)

Bruno Franco
Bruno Franco

Reputation: 2037

I tested your code, it is working, just make sure you are openning and closing your fors correctly.. Here is my code sample:

public class Main {

    public static void main(String[] args) throws ParseException {

        String[] array = new String[10];
        array[0] = "teste1";
        array[1] = "teste2";
        array[2] = "asdf3";
        array[3] = "dfg4";
        array[4] = "xcv";
        array[5] = "324dfg";
        array[6] = "der";
        array[7] = "a";
        array[8] = "sdf1";
        array[9] = "fgdfg7";

        isAscending(array);
    }

    public static void isAscending(String[] array) {

        for (String a : array) {
            System.out.println(a);
        }
        System.out.println("----------");
        Arrays.sort(array);

        for (String ao : array) {
            System.out.println(ao);
        }
    }

}

Output:

teste1
teste2
asdf3
dfg4
xcv
324dfg
der
a
sdf1
fgdfg7
----------
324dfg
a
asdf3
der
dfg4
fgdfg7
sdf1
teste1
teste2
xcv

Upvotes: 1

Related Questions