尝试使用for和while循环打印出2个三角形,用户输入n 但是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 :(得分: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.
}