Ciclo If (Condicional Multiple)
En su forma más general, la estructura IF - ELSEIF - ELSE: permite implementar condicionales más complicados, en los que se “encadenan” condiciones en la forma siguiente:
Si se verifica la condición 1, ejecutar las instrucciones del bloque 1.
Si no se verifica la condición 1, pero SI se verifica la condición 2 , ejecutar las instrucciones del bloque 2 .
Si no, esto es, si no se ha verificado ninguna de las condiciones anteriores, ejecutar las instrucciones del bloque 3. En cualquiera de los casos,elflujo del programa continuá por lainstrucción siguiente a la estructura IF - ELSEIF - ELSE.
La sintaxis en R es como sigue:
if(condición 1) {
result 1
} else if (condición 2) {
resultado 2
} else {
resultado 3
}
Si se verifica la condición 1, ejecutar las instrucciones del bloque 1.
Si no se verifica la condición 1, pero SI se verifica la condición 2 , ejecutar las instrucciones del bloque 2 .
Si no, esto es, si no se ha verificado ninguna de las condiciones anteriores, ejecutar las instrucciones del bloque 3. En cualquiera de los casos,elflujo del programa continuá por lainstrucción siguiente a la estructura IF - ELSEIF - ELSE.
La sintaxis en R es como sigue:
if(condición 1) {
result 1
} else if (condición 2) {
resultado 2
} else {
resultado 3
}
Ejemplo Condicional Multiple If
El profesor de cultura fisica de los cadetesde segundo año de aviacion militar desea implementar un programa donde se introduzca el numero de abdominales, flexiones de pecho y el tiempo del test de cooper del cadete. Sabiendo que si el cadete acumula menos de 65 abdominales, menos de 70 flexiones de codo y mas de 12 minutos en el test de cooper entonces el cadete no aprobara.
import javax.swing.JOptionPane;
public class formulario extends javax.swing.JFrame {
public formulario() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
txtca = new javax.swing.JTextField();
txtcf = new javax.swing.JTextField();
txtmt = new javax.swing.JTextField();
btnaceptar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel1.setText("TABLA DE PRUEBAS FISICAS");
jLabel2.setText("CANTIDAD DE ABDONIMALES");
jLabel3.setText("CANTIDAD DE FLEXIONES");
jLabel4.setText("MINUTOS EN EL TROTE");
txtca.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtcaActionPerformed(evt);
}
});
btnaceptar.setText("ACEPTAR");
btnaceptar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnaceptarActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(62, 62, 62)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(59, 59, 59)
.addComponent(txtmt, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(47, 47, 47)
.addComponent(txtcf, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(28, 28, 28)
.addComponent(txtca, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(41, 41, 41))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnaceptar)
.addGap(119, 119, 119))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(33, 33, 33)
.addComponent(jLabel1)
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtcf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtmt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addComponent(btnaceptar)
.addContainerGap(90, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void txtcaActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnaceptarActionPerformed(java.awt.event.ActionEvent evt) {
int ca=Integer.parseInt(txtca.getText());
int cf=Integer.parseInt(txtcf.getText());
double mt=Double.parseDouble(txtmt.getText());
if (ca<65){
JOptionPane.showMessageDialog(null, "No pasa pruebas fisicas");
}else if (cf<70){
JOptionPane.showMessageDialog(null, "No pasa pruebas fisicas");
}else if(mt>12){
JOptionPane.showMessageDialog(null, "No pasa pruebas fisicas");
}else{
JOptionPane.showMessageDialog(null, "Si Pasa pruebas fisicas");
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(formulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(formulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(formulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(formulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new formulario().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnaceptar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JTextField txtca;
private javax.swing.JTextField txtcf;
private javax.swing.JTextField txtmt;
// End of variables declaration
}
Interesante este aporte!.
ResponderEliminarGracias por la información
ResponderEliminarEs muy beneficioso y de mucha información
ResponderEliminarMe gustaria conocer mas sobre este tema, muy interesante
ResponderEliminarGracias por la información muy interesante
ResponderEliminarExcelente trabajo, muy benefisioso.
ResponderEliminarIncreible trabajo, felicitaciones
ResponderEliminarMuy buena página, su información es muy necesaria
ResponderEliminarmuy bien elaborado
ResponderEliminarEl aporte es interesante
ResponderEliminarIncreible trabajo, muchas gracias.
ResponderEliminarBuen aporte y buena informacion
ResponderEliminarnecesito aprender mas sobre el tema
ResponderEliminarGracias por este aporte
ResponderEliminarLa información que nos brinda este programa es muy util
ResponderEliminarIncreible trabjao, felicidades
ResponderEliminarmuy buen aporte muchas gracias
ResponderEliminargracias , muy buen aporte
ResponderEliminarel aporte de esta pagina es muy importante para el campo de la programacion
ResponderEliminarMe parece que la información es clara y de gran ayuda
ResponderEliminarbuen trabajo para diferentes condiciones :)
ResponderEliminarmuy util y practico
ResponderEliminar