我如何将这个for循环转换为while循环

我如何将这个for循环转换为while循环

本文介绍了我如何将这个for循环转换为while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我正在创建一个数组程序。我正在练习如何将循环转换为循环,但是我无法理解这个概念。 如果我有 for 循环: int [] list = new int [5]; for(int i = 0; i list [i] = i + 2; $ / code> 我如何使它成为而循环? 这是我的尝试 $ b $ pre $ int [ ] list = new int [5]; int i = 0; while(i list [i] = i + 2; i ++; } System.out.print(list [i] +); 这是我认为应该完成的事情,但在我的电脑中出现错误。 / p> 这是行21 System.out。 print(list [i] +); 解决方案一个基本的for语句的一般结构是: ForInit 是初始值设定项。它是首先设置变量等。 表达式是一个布尔条件来检查是否 Statement 应该运行 语句是要运行的代码块,如果 Expression 为true ForUpdate 在 Statement 例如根据需要更新变量 在 ForUpdate 再次评估c>表达式。如果它仍然是真的,再次执行 Statement ,那么 ForUpdate ;直到表达式为假。 您可以按如下方式将其重构为一个while循环: ForInit; while(Expression){ Statement; ForUpdate; $ b $为了将这个模式应用到一个真正的for循环,只需要替换如上所述。 以上例子: ForInit => int i = 0 / code> => i ForUpdate => i ++ 语句 => list [i] = i + 2; 我= 0; while(i list [i] = i + 2; i ++; } I am creating an array program. I am practicing how to convert for loops to while loops, but I cannot grasp the concept.If I have the for loop: int [] list = new int [5];for (int i = 0; i < 5; i++) { list [i] = i + 2;}How would I make it a while loop?Here's my attemptint [] list = new int [5];int i = 0;while (i<5) { list [i] = i + 2; i++;}System.out.print(list[i] + " ");This is what I think should be done, but it comes up as an error in my computer.This is line 21System.out.print(list[i] + " "); 解决方案 The general structure of a basic for statement is:for ( ForInit ; Expression ; ForUpdate ) StatementForInit is the initializer. It is run first to set up variables etc.Expression is a boolean condition to check to see if Statement should be runStatement is the block of code to be run if Expression is trueForUpdate is run after the Statement to e.g. update variables as necessaryAfter ForUpdate has been run, Expression is evaluated again. If it is still true, Statement is executed again, then ForUpdate; repeat this until Expression is false.You can restructure this as a while loop as follows:ForInit;while (Expression) { Statement; ForUpdate;}In order to apply this pattern to a "real" for loop, just substitute your blocks as described above.For your example above:ForInit => int i = 0Expression => i < 5ForUpdate => i++Statement => list [i] = i + 2;Putting it together:int i = 0;while (i < 5) { list[i] = i + 2; i++;} 这篇关于我如何将这个for循环转换为while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-26 06:59