Java中颠倒的直角三角形 [英] Upside down right triangle in Java
本文介绍了Java中颠倒的直角三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要这样做:
*****
****
***
**
*
我有这样的代码: (int i = 0; i <5; i ++)
for(int j = 5; j> i; j--)
{
System.out.print(*);
}
System.out.println();
输出:
pre > *****
****
***
**
*
我不知道如何实现空格。任何帮助表示赞赏。
解决方案
您需要使用两个for循环:一个用于空格的数量和一个用于 *
:
for(int i = 0; i <5 ; i ++){
for(int j = 0; j< i; j ++){
System.out.print();
}
(int j = i; j <5; j ++){
System.out.print(*);
}
System.out.println();
$ b $ Java $ 8解决方案:
IntStream.range(0,5).forEach(i - > {
IntStream.range(0,i).forEach(j - > System.out (); print());
IntStream.range(i,5).forEach(j - > System.out.print(*));
System.out.println ;
});
I need to do this:
*****
****
***
**
*
and I have this code:
for (int i=0; i<5; i++)
{
for (int j=5; j>i; j--)
{
System.out.print("*");
}
System.out.println("");
which outputs this:
*****
****
***
**
*
I cant figure out how to implement the spaces. Any help appreciated.
解决方案 You need to use two for-loops: one for the number of spaces and one for the number of *
:
for (int i = 0; i < 5; i++) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
for (int j = i; j < 5; j++) {
System.out.print("*");
}
System.out.println();
}
Java 8 solution:
IntStream.range(0, 5).forEach(i -> {
IntStream.range(0, i).forEach(j -> System.out.print(" "));
IntStream.range(i, 5).forEach(j -> System.out.print("*"));
System.out.println();
});
这篇关于Java中颠倒的直角三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文