2016-11-30 9 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

당신은 루프 동안 외부의 끝에 J에 1을 할당 잊어 버린.

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

출력 :

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



희망 당신이 ...