2016-09-22 84 views
-4

enter image description here创建使用循环2个三角形和while循环

尝试使用和while循环与n由用户输入打印出2个三角形。
但while循环,我不能把它打印出来的三角形 它应该是这样的:

n = 3 
*X 
*X X 
*X X X 
*X 
*X X 
*X X X 

但它打印出这样的

X 
X X 
X X X 
X 
X 
X 
X 
X 
X 
import java.util.*; 
public class Triangle 
{ 
public static void main(String[] args) 
{ 
    Scanner input = new Scanner(System.in); 
    int n, number, count=0, count1; 

    System.out.print("Please enter an integer number: "); 
    n = input.nextInt(); 

    if (n>0) 
    { 
     for(int i = 1; i<=n; i++) 
     {  
      for(int j=0; j<i;j++) 
      System.out.print(" X"); 


      System.out.println(""); 


     } 

     while(count<n) 
     { 
      count = count +1; 
      count1 = 0; 
      while(count1 < count) 
      { 

       System.out.print(" X"); 
       System.out.println(""); 

       count1 = count1 + 1; 
      } 
     } 


    } 
    else 
    { 
    System.out.print("Invalid number! Enter the number again!"); 
    } 

    } 
    } 

回答

0

看看在你的while循环中。你在内部while循环中有System.out.println("");。就像使用for循环的版本一样,System.out.println("");应该在处理内部while循环后调用。

while(count<n) //outer 
{ 
    count = count +1; 
    count1 = 0; 
    while(count1 < count) //inner 
    { 
     System.out.print(" X"); 
     count1 = count1 + 1; 
    } 
    System.out.println(""); // Thats the right place. 
}