简体   繁体   English

在Java中将for循环翻译为while并执行while循环

[英]Translate for loop to a while and do while loop in Java

I created a couple for loops that print lines as such (each new number starts a new line, it doesn't show here): 我为循环创建了几个这样的行(每个新数字都以新行开头,此处未显示):

1 1
22 22
333 333
4444 4444

etc. until it reaches 9 then goes back down to 1. 以此类推,直到达到9,然后又回落到1。

I am supposed to translate it into both a while and do while loop and have been trying for the past hour and can't seem to do it. 我应该将其转换为一会儿并执行一会儿循环,并且在过去一个小时内一直在尝试,但似乎无法做到。

public static void main(String[] args) {  
   for (int x=1;  x <= 9; x++) {
       for (int y = 1; y <=x ; y++){
           System.out.print( x + "");
           }
       System.out.println();
       }

    // TODO code application logic here
  for (int x=9;  x >=1; x--) {
       for (int y = 1; y <=x ; y++){
           System.out.print( x + "");
           }
       System.out.println();

       }   int y =1;
  int x = 1;
  while (x <9){

      while (y <=x){
          y++;
  System.out.print(x +"");{
  }
  System.out.println();
}
 x++;
}

A for loop statement has three parts in the for (init; condition; post) . for循环语句在for (init; condition; post)包含三个部分。 These parts are separated by semicolons. 这些部分之间用分号分隔。 The init part specifies an initial statement, the condition is what determines if the loop body is executed or not and the post specifies a post loop statement. init部分指定一个初始语句,条件是确定循环体是否执行的条件,而post指定一个post循环语句。

You can do the same thing with a while loop except that instead of a single statement, it is actually several statements. 您可以使用while循环执行相同的操作,除了实际上不是多个语句,而是多个语句。 However a while loop is not exactly like a for loop since the continue statement and how it behaves is a concern. 但是, while循环与for循环并不完全一样for因为continue语句及其行为方式令人担忧。 More about that later. 以后再说。

A hint is that the various parts of the for statement are separated by semicolons which are also used to separate statements in Java. 提示是, for语句的各个部分由分号分隔,分号也用于分隔Java中的语句。

Consider the following for loop source example. 考虑以下for循环源示例。

int i;
for (i = 0; i < 5; i++) {
  // for loop body
}

So you would have an init statement before the loop statement, i = 0 then the loop statement itself containing the condition, i < 5 , and as the last line in the loop before the closing curly brace, you would put the post loop condition, i++ . 因此,您将在循环语句之前有一个init语句, i = 0然后循环语句本身包含条件, i < 5 ,并且作为结束大括号之前循环的最后一行,您将放置循环后条件, i++

The do while is a bit more complicated because of when the while condition is evaluated. do while会因为计算while条件while更加复杂。 In both the for loop and the while loop, the condition is evaluated and if the expression is not true then the loop body is not executed at all, it is skipped. for循环和while循环中,都会对条件求值,如果表达式不为true,则根本不执行循环体,将跳过该条件。 In the case of the for loop, the init statement is executed and then the condition is evaluated to determine if the for loop body should be executed. 对于for循环,将执行init语句,然后评估条件以确定是否应执行for循环主体。 Since a while loop does not have an init statement as part of the while statement, the condition is evaluated and if not true, the while loop body is not executed. 由于while循环没有一个初始化语句作为的一部分while声明,评估条件,如果不属实, while没有执行循环体。

A do while loop has a condition that is not evaluated until after the first time through the do while loop body. do while循环具有直到通过do while循环主体的第一次后才评估的条件。 So the statements within the do while loop are always executed at least once. 因此, do while循环中的语句始终至少执行一次。 Then the do while condition is evaluated and if true, execution returns to the top where the do is and the do while loop body is executed again. 然后评估do while条件,如果为true,则执行返回do所在的顶部,并再次执行do while循环主体。

Some code of several variations of loops where the init is i = 0 and where the condition is i < 5 and the post is i++ . 循环的几种变体的一些代码,其中init为i = 0且条件为i < 5且post为i++ In all cases I have the variable i defined out side of the loop body. 在所有的情况下,我有可变i定义了循环体的侧面。 In the case of a for loop, defining the variable i within the for statement causes the scope of the variable i , its visibility, to be restricted to the for loop body which would not be the case for the other types of loops. for循环的情况下,在for语句中定义变量i会导致变量i的范围(其可见性)仅限于for循环主体,而其他类型的循环则不会。

int i;
for (i = 0; i < 5; i++) {
  // for loop body
}

int i = 0;
while (i < 5) {
  // while loop body
  i++;
}


int i = 0;
do {
  // do while loop body
  i++;
} while (i < 5);

I mentioned that what happens when the continue statement is executed can make a difference when comparing these forms of loops. 我提到过,执行continue语句时发生的情况在比较这些形式的循环时会有所不同。 The way to think of it is that when a continue statement is executed then there is a jump to the closing brace of the loop statement enclosing the continue statement. 想到的方法是,当执行一个continue语句时,将跳转到包含continue语句的循环语句的右括号。 So this introduces something to consider. 因此,这引入了一些考虑因素。

Look at the above examples but with a continue statement. 看上面的例子,但带有一个continue语句。 In all of the examples below there is a continue statement which causes execution to skip to the end of the loop body when the variable i has a value of 3. 在下面的所有示例中,都有一个continue语句,当变量i的值为3时,该语句使执行跳至循环主体的末尾。

With this change the for loop will continue incrementing the variable i because it's post, the third part of the for statement, is executed at the end of the loop. 进行此更改后, for循环将继续增加变量i因为它的发布( for语句的第三部分)是在循环结束时执行的。 However with the while loop and the do while loop, the incrementing of the variable i is part of the loop body so when the continue is executed skipping to the end of the loop, the increment of the variable i is also skipped. 但是,对于while循环和do while循环,变量i的递增是循环主体的一部分,因此当执行continue跳至循环末尾时,变量i的递增也将被跳过。

int i;
// first time init variable i to zero then evaluate condition
for (i = 0; i < 5; i++) {  //  evaluate condition and execute loop body if true
  // for loop body
  if (i == 3)
      continue;  // when i == 3 continue is executed to skip to end of loop
}  // at point of braces, post executed, condition evaluated

int i = 0;
while (i < 5) {     // evaluate condition and execute loop body if true
  // while loop body
  if (i == 3)
      continue;  // when i == 3 continue is executed to skip to end of loop
  i++;      // variable i only incremented when this statement is executed
}  // braces indicate end of loop so jump back to top of loop


int i = 0;
do {
  // do while loop body
  if (i == 3)
      continue;  // when i == 3 continue is executed to skip to end of loop
  // more statements which may be skipped by the continue
  i++;      // variable i only incremented when this statement is executed
} while (i < 5);  // evaluate condition and jump to top of loop if true

You could make a change to the do while loop while condition to move the incrementing of the variable i into the while condition evaluation by using a pre-increment operator, the ++ operator, on the variable as in the following. 您可以对do while循环while条件进行更改,以通过在变量上使用预递增运算符++运算符,将变量i的增量移入while条件评估中,如下所示。 We use the pre-increment operator because we want to increment the variable i before we check its value. 之所以使用pre-increment运算符,是因为我们要在检查变量i的值之前对其进行递增。

int i = -1;    // need to start at -1 since the while will increment at beginning of the loop
while (++i < 5) { // increment variable i, evaluate condition and body of loop if true
  // while loop body
  if (i == 3)
      continue;  // when i == 3 continue is executed to skip to end of loop
}  // braces indicate end of loop so jump back to top of loop

int i = 0;
do {
  // do while loop body
  if (i == 3)
      continue;  // when i == 3 continue is executed to skip to end of loop
  // more statements which may be skipped by the continue
} while (++i < 5);  // increment variable i, evaluate condition and jump to top of loop if true

A for loop is a construct that is extremely similar to a while loop , except that it provides some extra niceties that reduce boilerplate code . for循环是一种与while循环极为相似的构造,不同之处在于它提供了一些额外的细节,可以减少样板代码

The beginning of a for loop sets your initial variable (in your case, x), your condition clause ( x <= 9 ) and your incrementor ( x++ ). for循环的开始设置您的初始变量(在您的情况下为x),条件子句( x <= 9 )和增量器( x++ )。 A while loop does not do these things for, it simply runs a block of code while the condition clause in the () is met. while循环不执行这些操作,它只是在满足()的condition子句的情况下运行一段代码。

Converting a for loop to a while is simple- for循环转换for while很简单-

for(int x = 0; x < 10; x++) {

int x = 0;
while(x < 10) {
    x++;
}

The while loop has all the same features as the for loop, but without the syntactic sugar. while循环具有与for循环相同的所有功能,但是没有语法糖。 This should help you convert the loops in your question, and in general. 通常,这应该可以帮助您转换问题中的循环。

Try this as your while loop: 试试这个作为while循环:

int y = 1;
int x = 1;

while (x < 9) {

    y = 1;
    while (y <= x) {
            y++;

        System.out.print(x + "");


    }
    System.out.println();
    x++;
}

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

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