ClubEnsayos.com - Ensayos de Calidad, Tareas y Monografias
Buscar

La sentencia switch


Enviado por   •  14 de Febrero de 2012  •  Informes  •  1.676 Palabras (7 Páginas)  •  728 Visitas

Página 1 de 7

La sentencia switch

Al contrario de if-then e if-then-else, la sentencia switch permite cualquier cantidad de rutas de ejecución posibles.. Un switch funciona con los datos primitivos byte, short, char e int. También funciona con tipos enumerados (tratados en Clases y herencia) y con unas cuantas clases especiales que «envuelven» a ciertos tipos primitivos: Character, Byte, Short, and Integer (tratado en Clases y objetos ).

El siguiente programa, SwitchDemo, declara un int llamado month cuyo valor representa un mes del año. El programa muestra el nombre del mes, basado en el valor de «month», mediante la sentencia switch.

/*

* 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 SwitchDemo {

public static void main(String[] args) {

int month = 8;

switch (month) {

case 1: System.out.println("Enero"); break;

case 2: System.out.println("Febrero"); break;

case 3: System.out.println("Marzo"); break;

case 4: System.out.println("Abril"); break;

case 5: System.out.println("Mayo"); break;

case 6: System.out.println("Junio"); break;

case 7: System.out.println("Julio"); break;

case 8: System.out.println("Agosto"); break;

case 9: System.out.println("Septiembre"); break;

case 10: System.out.println("Octubre"); break;

case 11: System.out.println("Noviembre"); break;

case 12: System.out.println("Diciembre"); break;

default: System.out.println("Mes no válido.");break;

}

}

}

En este caso se mostrará «Agosto» en la salida estándar.

El cuerpo de una sentencia switch se conoce como el bloque switch. Cualquier sentencia contenida directamente por el bloque switch puede estar marcada por una o más etiquetas case o default. La sentencia switch evalúa su expresión y ejecuta el caso (case) adecuado.

También es posible, por supuesto, conseguir el mismo resultado con sentenciasif-then-else:

int month = 8;

if (month == 1) {

System.out.println("Enero");

} else if (month == 2) {

System.out.println("Febrero");

}

. . . // etcétera

La decisión de usar una sentencia if-then-else o switch a menudo es simplemente una cuestión de criterio

...

Descargar como (para miembros actualizados)  txt (7.5 Kb)  
Leer 6 páginas más »
Disponible sólo en Clubensayos.com