问题
I am trying to print the following using a nested loop in Java:
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
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
回答1:
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 +" ");
}
}
回答2:
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
回答3:
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();
}
回答4:
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();
}
回答5:
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(" ");
}
}
}
回答6:
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();
}
来源:https://stackoverflow.com/questions/15463925/java-to-print-number-triangle-with-nested-loop