我想在java程序中为pryamid打印以下格式

时间:2017-04-22 18:45:10

标签: java

1**
2**
3***
4****

直到那时我才得到这段代码

public class triangles {
    public static void main(String[] args) {
        for (int i = 1; i <= 4; i++) {     
            for (int j = 0; j < i; j++) {        
                System.out.print("*");
            }    
            System.out.println("");
        }
    }
}

3 个答案:

答案 0 :(得分:0)

您可以在循环之前打印索引:

for (int i = 1; i <= 4; i++) {
    System.out.print(i);//<<----------Print the index i
    for (int j = 0; j < i; j++) {
        System.out.print(i == 1 ? "**" : "*");//check if i == 1 then print 2 stars else 1
    }
    System.out.println("");
}

如果您的意思是 1* ,则可以将System.out.print(i == 1 ? "**" : "*");替换为System.out.print("*");

答案 1 :(得分:0)

你只需要添加i索引进行打印 你去吧

public class triangles {
public static void main(String[] args) {
    for (int i = 1; i <= 4; i++) { 
           system.out.println(i);
        for (int j = 0; j < i; j++) {        
            System.out.print("*");
        }    
        System.out.println("");
    }
}

}

答案 2 :(得分:0)

Java 8简化了它:

public class triangles {
    public static void main(String[] args) {
        for (int i = 1; i <= 4; i++) {   
            System.out.print(i);
            System.out.println(String.join("", Collections.nCopies(i, "*")));
        }
    }
}