Ir al contenido principal

Instrucciones de control

A continuación se presenta un ejemplo, con los diferentes usos para estructuras condicionales y de iteración.
El ejemplo es totalmente funcional y nos muestra en el método "ifCondicionalStatement()" las  instrucciones condicionales, las diferentes formas de utilizar la sentencia, if, else, switch y una forma opcional de implementar un switch con un mapa, con la ventaja de poder switchear valores mas alla de los primitivos. El método "iterateStatement()" contiene diferentes ejemplo para utilizar, while, for, además de instrucciones como; continue, break, etc.

package com.avventa.training.java.class4;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class ControlStatements {

public static void main(String[] args) {
System.out.println("** ifCondicionalStatement **");
ifCondicionalStatement();
System.out.println("** iterateStatement **");
iterateStatement();
}
/**
* Some examples of conditional statement: 
* Basic statement:
* if ([conditional]) {
*   
*   // do something
* }
*/
public static void ifCondicionalStatement () {
int i = 10;
int j = 20;
// Basic statement
if (i == 10) {
System.out.println("i is 10!");
}
// Two conditional statements and else.
if ( (i != 10) || 
(j == 20)) {
System.out.println("i != 10 or j == 10");
} else {
if (i == 10) {
System.out.println("i is 10 in the else statement");
}
}
// setting and conditional comparation.
if ((i = i + j) == 30) {
System.out.println(" i == 30 ");
}
switch (i) {
case 1:
System.out.println(" case 1 ");
break;
case 10:
System.out.println(" case 10 ");
break;
default:
System.out.println(" Default ");
break;
}
// Map instead of switch.
Map switchMap = new HashMap ();
i = 0;
switchMap.put(i++, " case 1 ");
switchMap.put(i++, " case 2 ");
i = 1;
System.out.println("switchMap.get(i) = " + switchMap.get(i));
} // ifCondicionalStatement.
public static void iterateStatement () {
String [] stringArray = new String [] {"one", "two", "three", "four"};
int index = 0;
System.out.println("while statement\n");
// while statement.
while (index <= stringArray.length) {
System.out.println("index = " + index);
if (index % 2 == 0) {
System.out.println("Doing continue with index = " + index);
index += 1;
continue;
}
index += 1;
}
System.out.println("do ... while\n");
// do ... while.
index = 0;
do {
System.out.println("index = " + index);
if (index > (stringArray.length / 2)) {
break;
}
index += 1;
} while (index <= stringArray.length);
System.out.println("for statement\n");
// for statement.
for (int i = 0; i <>
System.out.println("i = " + i);
}
System.out.println("foreach\n");
// for each.
for (String string : stringArray) {
System.out.println(string);
}
System.out.println("foreach with ArrayList\n");
// for each.
for (String string : Arrays.asList(stringArray)) {
System.out.println(string);
}
} // iterateStatement.
} // E:O:F:ControlStatements.

Comentarios

Anónimo dijo…
well.. it's like I said!

Entradas más populares de este blog

Pasos para remover Postgresql 8.3 en MAC OS

Tomado de: http://forums.enterprisedb.com/posts/list/1437.page In Mac OSX: (Assuming Default Locations) Via uninstaller: 1) In the installation directory, there will be a uninstall-postgresql.app file will be there, executing (double clicking) that will uninstall the postgresql installation. Manual Uninstallation: 1) Stop the server sudo /sbin/SystemStarter stop postgresql-8.3 2) Remove menu shortcuts: sudo rm -rf /Applications/PostgreSQL 8.3 3) Remove the ini file sudo rm -rf /etc/postgres-reg.ini 4) Removing Startup Items sudo rm -rf /Library/StartupItems/postgresql-8.3 5) Remove the data and installed files sudo rm -rf /Library/PostgreSQL/8.3 6) Delete the user postgres sudo dscl . delete /users/postgres

Validaciones con HTML5 sin necesidad de form.submit

Como parte de HTML5 existe la posibilidad de agregar información a los inputs de un form, para realizar validaciones; podemos indicar si queremos que sea requerido, con el tipo de datos; number, email, etc restringimos los valores que pueden ser agregados, podemos usar alguna mascara para validaciones, colocar mensajes de error custom, etc (en la red existen muchos ejemplos acerca de como customizar formularios). Ahora bien pongamos en contexto, tengo un formulario como este: <form name="managerForm"  id="managerForm">              <p>                  Name:                 <input id="managerNameText" required="required" placeholder="Write here the new manager name" size="40"/>              </p>             <p>                 Email:                 <input id="emailText" required="required" placeholder="myemail@myserver.com" type="email" />

Inventario anual de bebidas

Hola gente, Solo quería compartir mi inventario anual de bebidas (así conocer gustos), excluyendo algunas cervecillas que tengo por ahí guardadas, este es mi inventario: Ron: Flor de Cana 1 botella 5 anos. 2 botellas 7 anos una pacha 7 anos 2 botellas 12 anos 1 botella 18 anos Ron Zacapa 15 anos Centenario pachita 7 anos Centanario pachita 12 anos Bacardi limon Bacardi Razz Ron abuelo 7 anos Bacardi superior 1862 Ron Boltran XL Ron Centenario Garrafon Ron Jamaica Appleton 7 anos Ron Jamaica Appleton 12 anos (muchisimas gracias a Mayra :) Capitan Morgan Rum Jumbie, coconnut splash Ron coconut Malibu Ron Tequila Milagro Silver (muchisimas gracias a Pablito :) Sauza Gold Sauza Reposado Don Julio Reposado Vino Luigi Borer Malbec 2006 Casillero del Diablo, Caberut Sauviguon 2009 Vodka 2 botellas smirnoff y una smirnoff con sabor cranberry Cremas y otro licores Cahuita pacha Amaretto Barinet Licor de menta Licor de agave Rancho Escondido Bayleys 2 botellas (muchisimas gracias a Brian B :) Li