-1

I currently creating a program using Java + Selenium WebDriver, currently having a difficulty of looping technique in Java.

Below is my code:

Assume,

rt = {Capacity Utilization,Overlay Report}

fq = {15 Minute,Hourly,Daily}

Code::

    for( String rt : rep_type ) {
         new Select(driver.findElement(By.name("reporttype"))).selectByVisibleText(rt);
            for( String fq : freq ){

                try {
                Thread.sleep(2000);
                new Select(driver.findElement(By.name("frequency"))).selectByVisibleText(fq);
                Thread.sleep(3000);
                } catch (Exception e){
                    e.printStackTrace();
                }

                Thread.sleep(1500);

                try {
                    WebElement selectElement = driver.findElement(By.id("firstPeriod"));
                    Select select = new Select(selectElement);
                    List<WebElement> opts = select.getOptions();
------
-----
----
--
-

The problem is, when 'rt' equal to "Overlay Report", there are no element for this report to match the String in 'fq' array. Hence, it will proceed to the next code within the same loop.

How I can jump into the initial loop again which is,

for( String rt : rep_type ) {

so it will not proceed to the next code when there are no condition met with 'fq' array.

MrAZ
  • 394
  • 3
  • 13
  • 1
    Please check your indentations... I don't get your "problem", "_Hence, it will proceed to the next code within the same loop._" what code, what loop? Please be specific. See [ask]. – AxelH Mar 20 '18 at 10:32

2 Answers2

2

You can label your loop and use it just like this:

myLoopForInitialCycle:
for(Smth smth : smths) {
    ...
    for(Smth smth2: smths2) {
        if (smth.equals(smth2) {
             continue myLoopForInitialCycle;
        }
    }
}

This smells like structural style, and some measures have to be executed to avoid it, but I think this is just what you are asking for.

nyarian
  • 4,085
  • 1
  • 19
  • 51
  • Note : [Should I avoid using Java Label Statements?](https://stackoverflow.com/q/46496/4391450). Those answers show that's a tricky subject, as of today I never had to use one and never had to try to avoid them either. – AxelH Mar 20 '18 at 11:18
  • @AxelH, I warned about this technique in my answer. But it is just the exact answer for the exact question: "how can I jump to external cycle?", nothing more or less – nyarian Mar 20 '18 at 12:41
1

You're looking for either the break or continue keywords. When called from within a loop they will either break out of the loop or skip to the end of the current iteration.

So, your potential solution will look like this:

for( String rt : rep_type ) {
  if ("Overlay Report".equals(rt)) {
    continue;
  }
  // rest of code
A. Bandtock
  • 1,233
  • 8
  • 14