'Test list of list grid row by row

givenC:

public void testByRow1() {

    List<List<String>> grid = new ArrayList<List<String>>();
    grid.add(new ArrayList<String>());
    grid.get(0).add("hello ");
    grid.get(0).add("there!");

    grid.add(new ArrayList<String>());
    grid.get(1).add(null);
    grid.get(1).add(" How's it going?");

    String gotBack = Drill05.byRow(grid);
    String expected = "hello there! How's it going?";
    System.out.println(
            "byRow: expected = " + expected + ", gotBack = " + gotBack);
    assertEquals(expected, gotBack);
}

myC:

public static String byRow(List<List> grid) {

    String sentence;
    String ans = "";
    String pull ="null";
    
     //Nested for loop goes through the grid and 
    for(int i =0; i <= 1; i++)
        for(int j = 0; j<= 1; j++) {
            sentence = grid.get(i).get(j);
            sentence = sentence + " ";
            
            //this takes the String sentence and removes 
            //null and puts in it's place a " " string
            if(sentence.contains(pull)) {
                ans = sentence.replace(pull, " ");
                return ans;
            }else
                return ans;
        }
    return ans;    
}

Hello I am new to this whole data structure coding stuff and my problem is that I have to go through a list of list grid and make a sentence of the elements. Once that sentence has been made, I have to replace "null" with a " " empty string. The above code for givenC and myC works when it is all in the same method together but when I put the code into the respective separate methods, the code no longer works. There are three return statements in the Myclass because that was the brute force way of how my IDE was telling me to fix my errors. I been working all day on trying to figure this out and had no luck at all. I have to submit this in a few hours and I can't find anything online or in class lectures similar to the problem I'm having that works. Please help me understand what to do to fix this bug and why its occurring!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source