繁体   English   中英

伪代码解释器:java while

[英]pseudocode interpreter: java while

 for x = 0 to 9
 set stars = "*"
 set count = 0
 while count < x
 stars = stars + "*"
 count = count + 1
 endwhile
 display stars
 endfor

这是伪代码,这是我到目前为止所做的

for(int i=0;i<9;i++) {  
   for(int j=0;j<9-i;j++) {
System.out.print(" ");
  }
   for(int k=0;k<=i;k++) {
   System.out.print("* ");
  }
  System.out.println();

我需要更改此代码,使其同时使用 FOR 和 WHILE,但我只能管理 FOR。

任何 for 循环都可以写成 while 循环,只需在组件周围移动:

for (init; check; update) {
    body...
}

init;
while (check) {
    body...
    update;
}
        for (int i = 0; i < 9; i++)
        {
            String stars = "";
            int count = 0;
            while (count < i)
            {
                stars += "*";
                count++;
            }
            System.out.println(stars);
        }

根据您的伪代码:

set count = 0
while count < x
    stars = stars + "*"
    count = count + 1

你可以改变你的内部循环:

for (int k = 0; k <= i; k++) {
    System.out.print("* ");
}

进入:

int k = 0;
while (k <= i) {
    System.out.print("* ");
    k++;
}

对于上述伪代码,您可以使用以下 Java 代码

String star = '*';
int count =0;

for(int x =0; x < 9; x++)
{
  count =0;
  while(count < x)
  {
    star += star;
    count++;
  }
  System.out.println(star);
}

如果你知道,a forwhile可以很容易地相互转换:

for (a;b;c) {
    d;
}

实际上(大部分)意味着

a;
while(b) {
    d;
    c;
}

提醒一下,在for x = 0 to 9伪代码中for x = 0 to 9实际上意味着for (x = 0; x < 10; x++)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM