Home > Enterprise >  I can't understand why break is not working
I can't understand why break is not working

Time:12-22

So I am trying to write a function that checks if there is duplicates inside an array. Once the function detects a duplicate I want it exit break out of the loop and return type. However in my case it keeps on looping as if the break does not exist. Can please someone explain for me why this happening?

 public static boolean singleNumber(int[] nums) {
           boolean type = false;
           for (int i = 0; i < nums.length - 1; i  ) {
              for (int j = i   1; j <= nums.length - 1; j  ) {
                   if (nums[i] == nums[j]) {
                        type = true;
                        break;
                  }
               }
             }
             return type;
           }

CodePudding user response:

The break will only get out of the inner loop, not both loops. One option is to just return true instead of break. And return false at the end of the method if there is no early return. No need for the type variable in this case.

CodePudding user response:

your present logic keeps on iterating all the elements even if it finds a duplicate value. To change that, you need to check the type value in the outer for loop and if it is true, then you can break from that loop and return the value.

Though your present logic will help in identifying the duplicate values, it will be an overhead once the value is found as it will keep on iterating the array.

Here is the solution that should suit your requirement:

public class Main {
public static void main(String[] args) {
    System.out.println( singleNumber(new int[]{1,3,1}) );
}

 public static boolean singleNumber(int[] nums) {
       boolean type = false;
       for (int i = 0; i < nums.length - 1; i  ) {
          for (int j = i   1; j <= nums.length - 1; j  ) {
               if (nums[i] == nums[j]) {
                    type = true;
                    break; // to break out of the inner for loop
              }
           }
           if( type)   
           {
               break; // to break out of the outer for loop
           }
         }
         return type;
       }

}

CodePudding user response:

The breakstatement has no effect in an if statement. You can only use it for switch , for , while and do

In your code the break ends the for loop, not the if.

You could return a boolean instead of a break

  • Related