|
NOTA: La traducción de esta documentación es un esfuerzo personal y voluntario, no es un documento oficial de Sun Microsystems
ni Oracle ni está patrocinado por ninguna de estas empresas. Los documentos originales (en inglés) están disponibles en:
http://java.sun.com/docs/books/tutorial/.
Dirija cualquier comentario, petición, felicitación, etc. a tutorialesjava_@RROBA_codexion.com. |
Si desea ayudar a mantener en funcionamiento esta web, colaborar con la traducción de estos documentos o necesita que se traduzca algĂșn capĂtulo en concreto puede realizar una donación directa mediante Paypal:
|
La sentenciaforproporciona una forma compacta de recorrer un rango de valores. Los programadores a menudo se refieren a ella como el «bucle for» por la forma en la que recorre su bloque hasta que se satisfaga la condición indicada. La forma general de la sentenciaforse puede expresar del siguiente modo:Al usar esta versión de la sentenciafor (inicialización; terminación; incremento) { sentencia(s) }fortenga en cuenta que:
- La expresión inicialización inicializa el bucle, se ejecuta una sola vez cuando el bucle empieza.
- El bucle termina cuando la expresión terminación evalúa a
false.- La expresión incremento se invoca después de cada iteración por el bucle; es perfectamente aceptable que esta expresión incremente o decremente un valor.
El siguiente programa,
ForDemo, utiliza la forma general de la sentenciaforpara mostrar los números del 1 al 10 en la salida estándar:La salida de este programa es:/* * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ class ForDemo { public static void main(String[] args){ for(int i=1; i<11; i++){ System.out.println("Número: " + i); } } }Fíjese en cómo el código declara una variable dentro de la expresión de inicialización. El ámbito de esta variable se extiende desde su declaración hasta el final del bloque perteneciente a la sentenciaNúmero: 1 Número: 2 Número: 3 Número: 4 Número: 5 Número: 6 Número: 7 Número: 8 Número: 9 Número: 10for, por lo tanto también se puede usar en las expresiones de terminación e incremento. Es mejor declarar la variable que controla una sentenciaforen la expresión de inicialización si ésta no es necesaria fuera del bucle. A menudo se utilizan los nombresi,jykpara controlar los buclesfor; al declararlas dentro de la expresión de inicialización se limita su tiempo de vida y se reduce la posibilidad de error.Las tres expresiones del bucle
forson opcionales; se puede crear un bucle inifinto del siguiente modo:for ( ; ; ) { // bucle infinito // el código va aquí }La sentencia
fortambién tiene otra forma diseñada para la iteración a través de Colecciones y arrays. A esta forma a veces se la denomina for mejorado («enhanced for») y se puede utilizar para compactar más sus bucles y facilitar su lectura. Como ejemplo, fíjese en el siguiente array, que contiene los números del 1 al 10:int[] numeros = {1,2,3,4,5,6,7,8,9,10};El siguiente programa,
EnhancedForDemo, utiliza el bucleformejorado para recorrer el array:En este ejemplo la variable/* * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ class EnhancedForDemo { public static void main(String[] args){ int[] numeros = {1,2,3,4,5,6,7,8,9,10}; for (int elemento : numeros) { System.out.println("Número: " + elemento); } } }elementocontiene el valor actual del array «numeros». La salida de este programa es igual a la anterior:Se recomienda el uso de esta forma de la sentenciaNúmero: 1 Número: 2 Número: 3 Número: 4 Número: 5 Número: 6 Número: 7 Número: 8 Número: 9 Número: 10foren vez de la forma general siempre que sea posible.