java中循环数组学习_学习循环

java中循环数组学习

A significant advantage of computers is that they can perform repetitive tasks easily and efficiently. Instead of writing repetitive code you can write a set of statements that processes some data and then have the computer execute them repeatedly by using a construct known as a loop. Loops come in several different flavors in PHP: for, while, do-while, and foreach. I’ll introduce you to each of them and show you how they can making repetitive tasks straightforward and easy to maintain.

计算机的显着优势是它们可以轻松高效地执行重复性任务。 您可以编写一组处理某些数据的语句,然后让计算机使用称为循环的构造重复执行这些语句,而不必编写重复的代码。 循环在PHP中具有几种不同的风格: forwhiledo-whileforeach 。 我将向您介绍它们中的每一个,并向您展示它们如何使重复的任务简单明了且易于维护。

for循环 (The for Loop)

Let’s consider the example of generating a multiplication table for the number 12. You could calculate and display the values resulting from multiplying 12 by 1, 2, 3 etc. like so:

让我们考虑为数字12生成一个乘法表的示例。您可以计算并显示将12乘以1、2、3等所得的值,如下所示:

<?php
echo "1 × 12 = " . (1 * 12) . "<br>";
echo "2 × 12 = " . (2 * 12) . "<br>";
echo "3 × 12 = " . (3 * 12) . "<br>";
...

… and so on. Maybe extending the code to 12×12 would be quick, a simple matter of copy, paste, and amend. But what if the calculation needed to go up to 50×12? The copy and paste approach is really an inefficient use of your time and can lead to unwieldy code down the road.

… 等等。 也许将代码扩展到12×12很快,只需复制,粘贴和修改即可。 但是,如果计算需要增加到50×12,该怎么办? 复制和粘贴方法实际上是对您的时间的低效使用,并且可能会导致笨拙的代码。

But never fear! A solution is at hand – the for loop.

但是不要害怕! 一个解决方案就在眼前– for循环。

<?php
for ($i = 1; $i <= 12; $i++) {
    echo $i . " × 12 = " . ($i * 12) . "<br>";
}

This example shows how few lines are needed to create the multiplication table for any arbitrary value.

本示例说明了为任意值创建乘法表所需的行数。

There are three separate expressions used with a for loop which are separated by semicolons and contained within the parentheses:

for循环使用三个单独的表达式,用分号分隔并包含在括号中:

  • The first expression $i = 1 initializes the variable $i to be used as a counter ($i is a commonly used variable name for loop counters). The counter will be used to keep track of how many times the loop has executed.

    第一个表达式$i = 1初始化变量$i用作计数器( $i是循环计数器的常用变量名)。 计数器将用于跟踪循环执行了多少次。

  • The second expression $i <= 12 determines whether to stop the loop or proceed. In this case, the loop will execute 12 times. To be more precise the loop will continue while $i has a value less than or equal to 12. Once $i has a higher value, the loop will stop.

    第二个表达式$i <= 12确定是停止循环还是继续。 在这种情况下,循环将执行12次。 更确切地说,当$i的值小于或等于12时,循环将继续进行。一旦$i的值较大,循环将停止。

  • The third expression $i++ updates the counter. $i is incremented by 1 each time after the loop as completed a cycle. A cycle of a loop is also known as an iteration.

    第三个表达式$i++更新计数器。 循环完成后,每次循环后, $i都会增加1。 循环的循环也称为迭代。

From a maintenance perspective, if you need to change the code to extend the range up to 50×12, then only the value in the second expression needs to be changed:

从维护的角度来看,如果您需要更改代码以将范围扩展到50×12,则仅需要更改第二个表达式中的值:

<?php
for ($i = 1; $i <= 50; $i++) {
    echo $i . " × 12 = " . ($i * 12) . "<br>";
}

This is clearly better than adding 38 more lines of code!

这显然比添加38行代码更好!

Now what if you want to process in reverse i.e. multiplying 12 by 12, then 11, then 10, and so on? It’s easy if you simply adjust the three expressions.

现在,如果您要反向处理,即将12乘以12、11、10等,该怎么办? 如果仅调整三个表达式,这很容易。

<?php
for ($i = 12; $i > 0; $i--) {
    echo $i . " × 12 = " . ($i * 12) . "<br>";
}

$i is initialized to 12, the value the loop needs to start with. $i > 0 ensures the loop will only iterate while $i is 1 or greater. After each cycle, the value of $i is decremented by one.

$i初始化为12,即循环开始的值。 $i > 0确保循环仅在$i为1或更大时迭代。 在每个周期之后, $i的值减一。

whiledo-while循环 (The while and do-while Loops)

A for loop is suitable when you have to carry out a finite number of actions. There may be times though when you need to carry out repetitive actions for an unspecified number of iterations. In this circumstance either of the while or do-while loops is ideal.

当您必须执行有限数量的操作时,适合使用for循环。 有时候,有时您需要为未指定的迭代次数执行重复操作。 在这种情况下, do-while循环或do-while循环都是理想的。

This example illustrates a do-while loop that reads a file and prints the contents – you don’t know in advance how many lines of data there are in this file so using for would clearly not be suitable.

此示例说明了一个do-while循环,该循环读取文件并打印内容-您事先不知道此文件中有多少行数据,因此使用for显然不合适。

<?php
$file = "employees.csv";
$employeeFile = fopen($file, "r");
do {
    $data = fgets($employeeFile);
    echo $data . "<br>"; 
}
while (!feof($employeeFile));

Note that the do keyword precedes the opening brace and the while clause follows the closing brace. The loop will continue until reaching the end of the file, irrespective of whether there are 5 or 500 lines.

请注意, do关键字在大括号之前, while子句在大括号之后。 循环将一直持续到到达文件末尾,而不管是5行还是500行。

The same example as a while loop only looks like this:

与while循环相同的示例如下所示:

<?php
$file = "employees.csv";
$employeeFile = fopen($file, "r");
while (!feof($employeeFile)) {
    $data = fgets($employeeFile);
    echo $data . "<br>"; 
}

So how does this differ from do-while? There is a subtle but important difference – do-while will execute at least once because the end of file condition is checked only after the first iteration. The while loop begins execution only if we are not at the end of file.

那么,这与do-while有何不同? 有一个细微但重要的差异– do-while一次操作至少执行一次,因为仅在第一次迭代之后才检查文件结束条件。 仅当我们不在文件末尾时, while循环才开始执行。

foreach循环 (The foreach Loop)

You’ve seen a straightforward example of printing the multiplication table for the number 12. Let’s look now at another example, this time using an array. As the article Introduction to PHP Arrays points out, arrays are essentially indexed tables of data. Consider this array holding the months of the year:

您已经看到了一个打印数字12的乘法表的简单示例。现在让我们看另一个示例,这次使用数组。 正如《 PHP数组简介》一文中指出的那样,数组本质上是数据的索引表。 考虑以下包含一年中月份的数组:

==img1==

== img1 ==

To access the value, you need the associated key. To illustrate how you might use $i as a key as well as a counter, let’s print calendar months from an array called $months:

要访问该值,您需要关联的密钥。 为了说明如何将$i用作键和计数器,让我们从名为$months的数组中打印日历$months

<?php
$months = array("January", "February", "March", ... "Dec");
for ($i = 0; $i < 12; $i++) {
    echo $months[$i] . "<br>";
}

You are using the for loop like before but with two subtle differences – first, $i is initialized to 0 because the first item in an automatically-indexed array is 0. Second, the condition checks that the counter is less than 12 because the loop must stop once 12 items have been processed (key values 0 to 11 in the array).

您像以前一样使用for循环,但有两个细微差别–首先, $i初始化为0,因为自动索引数组中的第一项为0。第二,条件检查计数器是否小于12,因为循环一旦处理了12个项目(数组中的键值0到11)必须停止。

You may have guessed there is an alternative to using for. Yes, that alternative is foreach. It doesn’t require you to know in advance how many array elements there are or to keep track of a counter variable.

您可能已经猜到了使用for的替代方法。 是的,那个替代方法是foreach 。 它不需要您事先知道有多少个数组元素或跟踪计数器变量。

There are two variations of the foreach loop and I’ll show you both. The first retrieves just the value of each array element.

foreach循环有两种变体,我将向您展示。 第一个仅检索每个数组元素的值。

<?php
foreach ($months as $value) {
	echo $value . "<br>";
}

You can see how this is a simpler solution for iterating through an array than using for. Within the parentheses you provide the array name followed by the as keyword and a variable to which will be assigned the current element’s value. In this case, $months is the array and $value is the value variable. There is no need for counters or checking whether the loop should continue and, if the array size changes, there is no need to change any code.

您可以看到,与使用for相比,这是一种遍历数组的简单解决方案。 在括号内,您要提供数组名称,后跟as关键字和一个变量,该变量将被分配当前元素的值。 在这种情况下, $months是数组,而$value是value变量。 无需计数器或检查循环是否应该继续,并且如果数组大小发生更改,则无需更改任何代码。

In the other foreach variant you have access to the key as well as the value:

在另一个foreach变体中,您可以访问键和值:

<?php
foreach ($months as $key => $mon) {
	echo $key . " - " . $mon . "<br>";
}

Here $key => has been added to the expression, which allows you to access the key value.

这里$key =>已添加到表达式中,使您可以访问键值。

breakcontinue关键字 (The break and continue Keywords)

I’ve assumed throughout this article that you want to process a loop from start to finish. It is of course possible that you may want to exit from a loop early if a certain condition occurs. For this you can use the break keyword, as shown in the following modified example of the earlier do-while loop:

在本文中,我一直假设您想从头到尾处理一个循环。 当然,如果发生某种情况,您可能希望提早退出循环。 为此,您可以使用break关键字,如先前do-while循环的以下修改示例所示:

<?php
$file = "employee.sql";
$employeeFile = fopen($file, "r");
do {
    $data = fgets($employeeFile);
    if (strlen($data) == 0) {
        break; 
    }
    else {
        echo $data; 
    }
}
while (!feof($employeeFile));

Each line of the file is retrieved and checked – if the line is blank, break is used to exit the loop immediately. The while clause keeps the loop running as long as it has not yet reached end of the file.

检索并检查文件的每一行–如果该行为空白,则使用break可以立即退出循环。 while子句可以使循环保持运行状态,只要它尚未到达文件末尾即可。

If you do not want to exit from the loop, but instead carry on with the next iteration, use the continue keyword instead.

如果您不想退出循环,而是继续下一次迭代,请改用continue关键字。

摘要 (Summary)

In this article you’ve seen there are a variety of ways in which loops can be used for repetitive tasks and to make your code easier to maintain. I’d like to leave you with some tips on using loops:

在本文中,您已经看到了将循环用于重复性任务并使代码易于维护的多种方式。 我想给你一些使用循环的技巧:

  • Use for when you have a finite and known number of iterations.

    使用for ,当你有一个有限的和已知的迭代次数。

  • Use while or do-while when the number of iterations is not known but can be controlled by a condition (e.g. reaching the end of a file).

    当迭代次数未知但可以通过条件(例如,到达文件末尾)控制时,请使用whiledo-while

  • Use foreach when you need to process each element in an array.

    需要处理数组中的每个元素时,请使用foreach

  • If you need to break out completely from a loop, you can use break.

    如果需要完全脱离循环,可以使用break

  • If you want to skip the remaining statements for the iteration and continue on with the next one, you can use continue.

    如果要跳过其余的语句以继续执行下一个语句,则可以使用continue

Image via Marcio Jose Bastos Silva / Shutterstock

图片来自Marcio Jose Bastos Silva / Shutterstock

翻译自: https://www.sitepoint.com/loops/

java中循环数组学习

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值