I need help with this
1******
12*****
123****
1234***
12345**
123456*
1234567
Using 3 for loops this will be completed. i tried this
public class Pattren {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int i,j,k;
for (i = 1; i <= 7; i++)
{
for (j = 1; j <= i; ++j)
{
System.out.print((j)+("\n"));
for (k = 7 - i; k >= 1; k--)
{
System.out.print("* ");
}
}
}
}
}
But there is some logical problem with it. I need improvement in thos code. I got this output.
1
* * * * * * 1
* * * * * 2
* * * * * 1
* * * * 2
* * * * 3
* * * * 1
* * * 2
* * * 3
* * * 4
* * * 1
* * 2
* * 3
* * 4
* * 5
* * 1
* 2
* 3
* 4
* 5
* 6
* 1
2
3
4
5
6
7
An easier version would be
int i,j;
for (i = 1; i <= 7; i++)
{
for (j = 1; j <= 7; ++j)
{
if (j <= i) {
System.out.print(j);
}
else {
System.out.print("*");
}
}
System.out.println();
}
Output
1******
12*****
123****
1234***
12345**
123456*
1234567
Below is a solution with much fewer lines of code:
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
String s = "";
for(int i=1; i<=7; i++){
s += i;
sb.append(String.format("%-7s", s).replace(" ", "*")).append("\n");
}
System.out.println(sb.toString());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.