Search code examples
javaeclipseassert

How do I make a return type have the same output as a print function?


Say I have this snippet of a code:

public String toString() {
    for(int i = 0; i<states.length; i++) {
        System.out.println(states[i]+ " "); 
    }
    return " ";     
}

This takes values of an array and outputs this onto the console:

AL (Alabama) - Population: 4860545 
AK (Alaska) - Population: 741522 
AZ (Arizona) - Population: 6908642 

The purpose is actually to return instead of print those values so that the function can be checked using the assertEquals but when I change the code so that print is replaced by return as such:

public String toString() {
    for(int i = 0; i<states.length; i++) {
        return states[i]+ " "; 
    }
    return " ";
}

This still fails the assertEquals check and the error is on the for statement which says that when i is incremented at i++ it is "dead code"

How do I have it so the return type does the same as what the print statement is doing?


Solution

  • Probably, you want to concat these strings and not return the first one?

    public String toString() {
        StringBuilder result = new StringBuilder();
        for(int i = 0; i<states.length; i++) {
            result.append(states[i]);
            result.append("\n");
            }
        return result.toString();
    }