简体   繁体   中英

Why Return inside While Loop comes out of the Outer For Loop in Java

I am trying to solve a question which says: Write a function to find the longest common prefix string amongst an array of strings.

Input:

["baab","bacb","b","cbc"]

Inside while loop, if i use break it returns an empty string which is correct answer:

""

But if i use break, it returns:

"ba"

Below is my code:

class Solution {
    public String longestCommonPrefix(String[] strs) {
        String first=strs[0];
        
        for(int i=1;i<=strs.length-1;i++){
            char[] c1 = first.toCharArray();
            char[] c2 = strs[i].toCharArray();            
            int index=0;
            first="";
            int len=0;
            
            if(c1.length<c2.length)
                 len=c1.length;
                else
                     len=c2.length;
                
            if(len==0){
                return first;
            }
            while(index<=len-1){
                if(c1[index]==c2[index]){
                    first=first+c1[index];
                }else{
                    **return first;**
                }
                index++;
            }
        }
        return first;
    }
}

As per my understanding, when we return inside a while loop(which is the inner loop here), it should come out of that particular loop and not from the outer for loop, similar to break. Please help me understand why it is coming out of the for loop here.

As per my understanding, when we return inside a while loop(which is the inner loop here), it should come out of that particular loop and not from the outer for loop, similar to break.

That is a wrong assumption: according to the docs , the method returns when it reaches the return statement:

A method returns to the code that invoked it when it

  • completes all the statements in the method,
  • reaches a return statement, or
  • throws an exception (covered later),

whichever occurs first.

To break out of inner loops, see this question: How do I break out of nested loops in Java?

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