因为循环的行为不同

时间:2014-09-09 19:52:53

标签: java

这是一个小代码

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);
}

在上面,如果我只使用第一个for循环,我按照它们传递的顺序获取所有元素。如果我将它们放在一起,我就得不到输出。 (Log是一个与System.out.println相同的函数)

我犯了一些重大错误吗? 我看不出第二个循环不起作用的原因

日志方法:

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

INPUT ARRAY:     我从网页(使用Selenium)获取数组。这是执行该功能的功能(它完美运行并提供我期望的输出):

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;
}

以下是我的称呼方式:

isAscending(getEmail());

1 个答案:

答案 0 :(得分:1)

我测试了您的代码,它正常运行,只是确保您正确地打开和关闭fors .. 这是我的代码示例:

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);
        }
    }

}

输出:

teste1
teste2
asdf3
dfg4
xcv
324dfg
der
a
sdf1
fgdfg7
----------
324dfg
a
asdf3
der
dfg4
fgdfg7
sdf1
teste1
teste2
xcv
相关问题