Question

This is the question in Coding bat(the Java version):: Given an array of ints, return true if the array contains a 2 next to a 2 somewhere. has22({1, 2, 2}) → true has22({1, 2, 1, 2}) → false has22({2, 1, 2}) → false

This was my solution:

public boolean has22(int[] nums) {

  for (int i=0; i<nums.length-1;i++) {

     if (nums[i]==2 && nums[i+1]==2) {
         return true;
     }
     else {

        return false;
     } 
  }
}

Doesn't compile while this does..

public boolean has22(int[] nums) {

  for (int i=0; i<nums.length-1;i++) {

     if (nums[i]==2 && nums[i+1]==2) {
         return true;
     }
     else {

     } 
  }    
    return false;

}

Sorry if this is a stupid question but I'm confused about the brackets at the end.

Was it helpful?

Solution

Imagine a case when your argument is empty or null. Your first method doesn't compile, because it doesn't return a boolean value for all cases.

Your second method compiles, because it will return a boolean value in any case, after the iteration is complete.

OTHER TIPS

  public boolean has22(int[] nums) 
     {
      for (int i=0; i<nums.length-1;i++) 
       if (nums[i]==2 && nums[i+1]==2) 
         return true;  
       return false;
     }

You can write your program like above no need of braces. for each conditional statement one statement is always there if we want to associate more than one statement with any conditional statement then we provide {} braces for example if(some condition)
stmt1; no need of braces but if more than one statement then if(some condition) { stmt1; stmt2; }

so always remember more than one statement braces compulsory and to avoid problem when ever open a bracket just close at the same time and write inside that one it will let you some relax. Thanks asif aftab

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top