Reputation: 27
Sample input string:
bluej
Output:
b***b *l*l* **u** *e*e* j***j
(where '*' indicates a blank space)
I have done this much so far:
int n = s.length() - 1;
int i, j;
for (i = 0; i <= n; i++) {
for (j = 0; j <= (n + 1); j++) {
if (i == j || i == n - (j - 1))
System.out.print(s.charAt(i));
else {
System.out.print("*");
}
}
System.out.println();
}
But output is:
b****b *l**l* **uu** **ee** *j**j*
Upvotes: 0
Views: 96
Reputation: 3596
Just replace i == n-(j-1)
with i == n - j
and second for loops for (j = 0; j <= n+1; j++)
to for (j = 0; j <= n; j++)
:
int n = s.length() - 1;
int i, j;
for (i = 0; i <= n; i++) {
for (j = 0; j <= n; j++) {
if (i == j || i == n - j)
System.out.print(s.charAt(i));
else {
System.out.print("*");
}
}
System.out.println();
}
Upvotes: 2
Reputation: 76444
Step 1: Look at the number of characters. You are displaying 6 characters, while the expected output displays 5 characters. You need to change the end of the inner for, like this:
for(j=0;j<=(n);j++)
Step 2: You are expecting to have n+1
as the last index for j
, but it was changed to n
. You need to apply it:
if(i== j || i == n-(j))
Examples:
Upvotes: 2
Reputation: 1817
It Works:
String s = "bluej";
int n = s.length() - 1;
int i, j;
for (i = 0; i <= n; i++) {
for (j = 0; j <= (n); j++) {
if (i == j || i == n - (j))
System.out.print(s.charAt(i));
else {
System.out.print("*");
}
}
System.out.println();
}
}
Upvotes: 1
Reputation: 3200
2nd loop termination condition should be j<=n
.
if condition should be (i == j || i == n - j)
Testing your code in a debugger while checking the values of the involved variables would likely let you solve it yourself.
Upvotes: 2