Reputation: 25
My code takes 2 input numbers to create the rows and columns of a rectangle. In that rectangle, the user chooses 2 letters for the rectangle body but they have to alternate, like this: (without the dashes ofc)
-xxxxx
-r r r r r
-xxxxx
-r r r r r
Whenever I try to make them alternate, the rows usually end up like "xrxrx" or "xrrrr" instead of a single letter. I've tried adding them "filler.append(firstLetter + secLetter);" but it just results in numbers. This probably has a really easy solution but I just don't see it ha ha...(・_・;) Any hints would be greatly appreciated, thank you!
public static void recDraw ( int rows, int columns, char firstLetter, char secLetter){
StringBuilder filler = new StringBuilder();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
filler.append(firstLetter);
filler.append(secLetter);
}
filler.append('\n');
}
System.out.println(filler);
}
Upvotes: 1
Views: 332
Reputation: 566
Inside inner loop (with counter j), before appending the letter to StringBuilder filler, check whether it is Fistletter line or SecondLetter line by using modulus operation on i value. 'i' value is used because it represents the line/row.
public static void recDraw ( int rows, int columns, char firstLetter, char secLetter){
StringBuilder filler = new StringBuilder();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if(i%2 == 0){
filler.append(firstLetter);
} else{
filler.append(secLetter);
}
}
filler.append('\n');
}
System.out.println(filler);
}
Upvotes: 1
Reputation: 104
public static void rectDraw(String ch1, String ch2, int cols, int rows) {
String rect = "";
for (int i = 0; i < rows; i++) {
String line = "";
for (int j = 0; j < cols; j++) {
if (i % 2 == 0) {
line += ch1;
}
else {
line += ch2;
}
}
rect += line + "\n";
}
System.out.println(rect);
}
This solves your problem. You will want to look into the modulus operator for more information about why this works. You can take a look here.
Upvotes: 1
Reputation: 682
Try printing the value of i and j, you will get where you are getting wrong.
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
filler.append(firstLetter);
filler.append(secLetter);
}
filler.append('\n');
}
In your above code snippet add a check if
i is even, then add firstLetter
i is odd, then add secondLetter
Upvotes: 1