java 使用嵌套 while 循环打印星星金字塔
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40890013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using nested while loop to print pyramid of stars
提问by Mario Rudaru
I'm trying to print a pyramid of stars using nested while loops. I know I am able to achieve this using for loops but I want to do it with while loop instead. This is my code so far:
我正在尝试使用嵌套的 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++;
}
}
}
The output has to be like this:
输出必须是这样的:
*
**
***
****
*****
But my output is this:
但我的输出是这样的:
*
*
*
*
*
Any help is appreciated, thanks.
任何帮助表示赞赏,谢谢。
回答by fsulser
you have to reset j like this:
你必须像这样重置 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;
}
}
}
回答by Shahnur Isgandarli
You have forgotten to assign 1 to j at the end of the outer while loop.
您忘记在外部 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;
}
}
}
回答by Suraj Sangani
public static void main(String[] args) {
for(int i=0;i<10;i++){
for(int k=0;k<i;k++){
System.out.print("*");
}
System.out.println();
}
}
回答by Neeraj Sharma
Pyramid using two for loops:
金字塔使用两个 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();
}
output:
输出:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
Hope this the answer you are looking for...
希望这是您正在寻找的答案...
回答by Vishal
*Instead of initializing "j" at the beginning, include it in the first while loop that'll do the work.( * will be printed at the beginning of each row)
* 不是在开头初始化“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++;
}
}
}
回答by Arpit Aggarwal
#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");
}
}