Search code examples
javafor-loopnested-loops

Dead code on a nested for loop that returns a boolean


I am trying to complete an exercise that we received in class. The solution was not nor will ever be posted since it is not evaluated. I can't seem to figure it out. When I run this code I get a warning for dead code. Which makes sense because my code seems to not permit to iterate through the second sub-array. So, when all elements are the same for the first sub-array even when they aren't for the second the method returns true. Any idea of how to fix this? I'm pretty lost at this point.

public class Warmup2 {


public static void main(String[] args) { 
    int[][] arr = {{1,1},{6,6,7}};
    System.out.println(subArraySame(arr));
}
//method that takes a 2D-array and checks if the elements of the subarrays are all the same
public static boolean subArraySame(int[][] arr) {

    for(int i = 0; i<arr.length; i++) {
        for(int j = 0; j<arr[i].length-1; j++) {
            if(arr[i][j]==arr[i][j+1]) {
                return true;
            } else {
              return false;  
            }
        }
      }return false;

   }

 }

Solution

  • I guess you want this:

    public static boolean subArraySame(int[][] arr) {
        for(int i = 0; i<arr.length; i++) {
            for(int j = 0; j < arr[i].length-1; j++) {
                if(arr[i][j] != arr[i][j+1]) {
                    return false;
                }
            }
        }
        return true;
    }
    

    which returns true only if every subarray consists of equal items.
    Your code terminated the loop at the 1st iteration because the if/else statements both contained a return.