Reputation: 11
I am unsure as to why I'm getting a dead code warning for my for loops, and I also don't know why only 1 of the symbols is printed, rather than the desired rectangle.
public static String rectangle(int row, int col, char thing) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
String character = "" + thing;
return character;
}
return "\n";
}
return "";
}
I tried putting the String character above the for loops, but still the same error. I cannot use any System.out.print
in my code either. I tried int i = 1; i <= row
, also tried it without the return "";
but I get an error for "no string returned."
Upvotes: 0
Views: 71
Reputation: 1
The problem here is that as soon as inner for loop will finish for the first time it will return an empty line and last return statement is of no use and will only execute if row is zero and second problem is that you've declared the variable inside the loop which is only accessible inside the loop so you've to declare it before the loop to return it as an answer, so replace the first return statement with string or stringBuilder or whatever you're using and declare a inside the method outside the loop.
So this is how the code would look:
public static String rectangle(int row, int col, char thing) {
StringBuilder b = new StringBuilder();// using StringBuilder instead of string as it is faster
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
b.append(""+thing);
}
b.append( "\n");
}
return b+"";//converting StringBuilder to string
}
Upvotes: 0
Reputation: 391
The lines
}
return "\n";
}
return "";
}
will not normally run because after the first inner loop executes, you are returning the new line character as a string, terminating the function at that point. The compiler spots that, and hence you get the "dead code warning". The answer above (by @Mureinik) explains how to fix that.
Upvotes: 0
Reputation: 311938
The first return
will terminate the method on the first iteration of the loop. Instead of all those returns, you should append to the string and only return at the end:
public static String rectangle(int row, int col, char thing) {
String result = "";
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
String character = "" + thing;
result += character;
}
result += "\n";
}
return result
}
Having said that, using a StringBuilder
would probably be more performant:
public static String rectangle(int row, int col, char thing) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
result.append(thing);
}
result.append("\n");
}
return result.toString();
}
Upvotes: 1