我的侄女在学校做作业时问了我这个问题,我不知道该怎么做。
老师请他们使用Java中的3个for循环打印以下模式:
1******
12*****
123****
1234***
12345**
123456*
1234567
请帮忙。
谢谢!
答案 0 :(得分:3)
以前是我的作业
代码
for (int i = 1; i <= 7; i++) {
for (int j = 1; j <= i; ++j) {
System.out.print(j);
}
System.out.println("");
}
将显示
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("");
}
将显示
******
*****
****
***
**
*
最终
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("");
}
将显示
1******
12*****
123****
1234***
12345**
123456*
1234567
答案 1 :(得分:0)
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("");
}
}
答案 2 :(得分:-1)
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