我正在尝试使用嵌套while循环打印星形金字塔。我知道我能够使用for循环实现这一点,但我想用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 :(得分: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;
}
}
}
答案 1 :(得分: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;
}
}
}
答案 2 :(得分:0)
encode error
答案 3 :(得分: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();
}
输出:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
希望这是你正在寻找的答案......
答案 4 :(得分:0)
*而不是在开始时初始化“ j”,而是将其包含在将进行工作的第一个while循环中。(*将打印在每行的开始处)
public class WhileNest
{
public static void main(String[]args)
{
int rows = 5, i = 1;
while(i <= rows)
{
int j = 1;
while(j <= i)
{
System.out.print("*");
j++;
}
System.out.print("\n");
i++;
}
}
}
答案 5 :(得分:-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");
}
}