java Java用嵌套循环打印数字三角形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15463925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java to print number triangle with nested loop
提问by tmwebdeveloper
I am trying to print the following using a nested loop in Java:
我正在尝试使用 Java 中的嵌套循环打印以下内容:
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
but it's coming out like the following:
但结果如下:
1 2 3 4 5 6
2 3 4 5 6
3 4 5 6
4 5 6
5 6
6
1 2 3 4 5 6
2 3 4 5 6
3 4 5 6
4 5 6
5 6
6
Here is my code:
这是我的代码:
for (int i = 1; i <= 6; i++) {
for (int j = 1; j < i; j++)
{
System.out.print(" ");
}
for (int j = i; j <= 6; j++)
{
System.out.print(j + " ");
}
System.out.println();
}
Any help would be appreciated. Thanks
任何帮助,将不胜感激。谢谢
回答by Abhishek
int n = 7;
for (int i = 1; i <= n; i++) {
for (int j = 1; j < i; j++) {
System.out.println(" ");
}
for (int j = i; j <= 6; j++) {
System.out.println(j +" ");
}
}
回答by Hahahaha
for (int i = 2; i <= 7; i++) {
for (int j = 2; j < i; j++) {
System.out.print(" ");
}
for (int j = i; j <= 7; j++) {
System.out.print(j-1 + " ");
}
System.out.println();
}
回答by user2798256
This is giving the same output ... Please check
这是给出相同的输出......请检查
public static void main(String[] args)
{ int c=0;
for(int i=6;i>0;i--)
{
for(int k=0;k<c;k++)
{
System.out.print(" ");
}
for (int j=1;j<=i;j++)
{
System.out.print(j +" ");
}
c++;
System.out.println(" ");
}
}
}
回答by Ajay S
Set this condition in inner second loop.
在内部第二个循环中设置此条件。
for (int j = 1; j <= 7 - i ; j++)
Edit :
编辑 :
Complete code is
完整的代码是
for (int i = 1; i <= 6; i++) {
for (int j = 1; j < i; j++)
{
System.out.print(" ");
}
for (int j = 1; j <= 7 - i ; j++)
{
System.out.print(j + " ");
}
System.out.println();
}
回答by Piyas De
Your Program should be -
你的程序应该是 -
for (int i = 1; i <= 6; i++) {
for (int j = 1; j < i; j++)
{
System.out.print(" ");
}
for (int j = 1; j <= (6-i+1); j++)
{
System.out.print(j + " ");
}
System.out.println();
}
Thanks
谢谢
回答by Divya Motiwala
Try this :
试试这个 :
for (int i = 1; i <= 7; i++) {
for (int j = 1; j < i; j++)
{
System.out.print(" ");
}
for (int j = 1; j <= 7-i; j++)
{
System.out.print(j + " ");
}
System.out.println();
}
}