2017-04-22 46 views
-1
1** 
2** 
3*** 
4**** 

直到那时我有这个代码片断我想打印在Java程序中以下格式的pryamid

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(""); 
     } 
    } 
} 
+1

你的意思'1 *'或'1 **' ? –

+0

你的问题是什么?请清楚代码/输出的错误。 – 4castle

+3

我投票结束这个问题作为题外话,因为这是一个需求规格说明,而不是一个问题。请参阅:[为什么“有人可以帮助我?”不是一个实际的问题?](http://meta.stackoverflow.com/q/284236) –

回答

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("*");

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(""); 
    } 
} 

}

+0

这不会产生问题的输出 –

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, "*"))); 
     } 
    } 
}