[英]Create 2 triangles using for loop and while loop
尝试使用 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!");
}
}
}
看看你的 while 循环。 你有System.out.println("");
在你的内部 while 循环中。 就像在带有 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.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.