简体   繁体   中英

for loop execute only once

Code only executes once. Disclaimer: Well aware this is an infinite loop, wrote it this way as part of troubleshooting the problem.

update: There was an exception in my error log that got fixed and the problem is still the same, code only executes once I tried using the same for loop in the same code for a different task (printing a sentence) and it worked fine, problem must be with my JS code.

for(int i=0; i<i+1;i++) {
    ((JavascriptExecutor)driver).executeScript("window.open()"); 
    ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles()); 
    driver.switchTo().window(tabs.get(1));
    driver.get("https://www.google.com");
}

Code is executing only once because of an exception being thrown, OR maybe one or more of the network calls you are making is taking too long that makes you believe that the code is executing only once.

To confirm that the value i + 1 , which you are using in the for-loop isn't getting replaced by 1 , I ran the following loop on my machine:

for (int i = 0; i < i + 1; i++) {
    System.out.println(i);
}

...and it goes on to print numbers starting from 0.

I'm just going to clarify this point as an answer, as I expect the question will be removed.

The for loop isn't your problem. You are writing code which has an exception or is blocking the running thread. If you're using another thread to run this, a lack of an UncaughtExceptionHandler can allow it to skip being logged. Similarly the use of Callable<T> can result in exceptions being swallowed from personal experience (perhaps for the same reason?).

If you are blocking the thread running it, then that thread won't run anything else until the blocking method returns control to the context of where you called it.

Given you said you had cases where the loop "ran once" but still printed after, I'm going to go with it being an exception, and the way that you are running your test is flawed. This can be from an uncountable number of reasons, such as a folly System#exit / Runtime#halt call, threads, using a service to run the tests, or running them in some production environment like a game server or a phone (or... A browser?). For future cases, your questions should ideally be reproducible with nothing other than a main method and the code you provide. If you cannot make such an example, at minimum you should provide how you are testing it.

If you do all of that and still have the issue, I think it will either be obvious to you, or the people reading your question here will have a much easier time answering it for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM