3 回答

TA貢獻(xiàn)1850條經(jīng)驗(yàn) 獲得超11個贊
這曾經(jīng)是我的家庭作業(yè)
代碼
for (int i = 1; i <= 7; i++) {
for (int j = 1; j <= i; ++j) {
System.out.print(j);
}
System.out.println("");
}
將會呈現(xiàn)
1
12
123
1234
12345
123456
1234567
和
for (int i = 1; i <= 7; i++) {
for (int k = 7 - i; k >= 1; k--) {
System.out.print("*");
}
System.out.println("");
}
將會呈現(xiàn)
******
*****
****
***
**
*
最終的
for (int i = 1; i <= 7; i++) {
for (int j = 1; j <= i; ++j) {
System.out.print(j);
}
for (int k = 7 - i; k >= 1; k--) {
System.out.print("*");
}
System.out.println("");
}
將會呈現(xiàn)
1******
12*****
123****
1234***
12345**
123456*
1234567

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超11個贊
public static void printPattern(int n) {
for(int i=0; i<n; i++) {
for(int k=1; k<=i+1; k++) {
System.out.print(k);
}
for(int j=i+1; j<n; j++) {
System.out.print("*");
}
System.out.println("");
}
}

TA貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個贊
Are you sure question has been asked to solve by using 3 for loops?
As it is better to use less loop as much as we can. Secondly there is no requirement in problem to use third loop. you can find the desired result by using two loops:
public class Main
{
public static void main(String[] args) {
for (int i = 1; i <= 7; i++) {
for (int j = 1; j <= 7; j++) {
if (j <= i) {
System.out.print(j);
}
else
{
System.out.print("*");
}
}
System.out.println("\n");
}
}
}
output will be:
1******
12*****
123****
1234***
12345**
123456*
1234567
添加回答
舉報