2016-11-30 71 views
0

我试图使用嵌套while循环打印恒星金字塔。我知道我可以用for循环来实现这个功能,但是我想用while循环代替它。这是到目前为止我的代码:使用嵌套while循环打印恒星的金字塔

public class WhileNest 
{ 
    public static void main(String[]args) 
    { 
     int rows = 5, i = 1, j = 1; 

     while(i <= rows) 
     { 
      while(j <= i) 
      { 
       System.out.print("*"); 
       j++; 

      } 
      System.out.print("\n"); 
      i++; 

     } 
    } 
} 

输出必须是这样的:

* 
** 
*** 
**** 
***** 

但我的输出是这样的:

* 
* 
* 
* 
* 

任何帮助表示赞赏,感谢。

回答

0

你必须复位j是这样的:

public class test { 
    public static void main(String[] args) { 
     int rows = 5, i = 1, j = 1; 

     while (i <= rows) { 
      while (j <= i) { 
       System.out.print("*"); 
       j++; 

      } 
      System.out.print("\n"); 
      i++; 
      j = 1; 
     } 
    } 
} 
+0

啊哈答案!谢谢你的帮助,非常感谢。 –

0

你忘了在while循环外的末尾分配1到j。

public class WhileNest { 

    public static void main(String[] args) { 
     int rows = 5, i = 1, j = 1; 

     while (i <= rows) { 
      while (j <= i) { 
       System.out.print("*"); 
       j++; 
      } 
      System.out.print("\n"); 
      i++; 
      j = 1; 
     } 
    } 
} 
-1
#include <stdio.h> 
#include<math.h> 
int main() 
{ 
int i,j,n; 
char c='*'; 
printf("Enter the size of the triangle:\n "); 
scanf("%d",&n); 
int width=n; 
for(i=0;i<n;i++) 
{ 
    for(j=0;j<i;j++) 
    { 
     if(j == 0) 
     { 

      printf("%*c",width,c); 
      --width; 
     } 
     else 
     { 
      printf("%2c",c); 
     } 

    } 
printf("\n"); 
} 

} 
+0

请提供您的代码的更多信息,否则可能很难理解。 – PhilMasterG

0

使用两个for循环金字塔:

String STAR = "*"; 
    String SPACE = " "; 
    int SIZE = 10; 
    for(int i=0;i<SIZE;i++) { 
     int start = SIZE-i; 
     int end = (SIZE*2) - SIZE + i; 
     for(int j = 0; j<SIZE*2; j++) { 
      if(j>=start && j<=end && j%2 == i%2) { 
       System.out.print(STAR); 
      } else { 
       System.out.print(SPACE); 
      } 
     } 
     System.out.println(); 
    } 

输出:

 *   
    * *   
    * * *  
    * * * *  
    * * * * *  
* * * * * *  
* * * * * * * 



希望这你正在寻找...