martes, 4 de noviembre de 2014

Programas Realizados 3er Periodo

1.-Solicitar el ingreso de un nombre y edad de 2 personas,Mostrar el nombre de la persona con mayor edad.
import java.util.Scanner;
public class CadenaDeCaracteres1 {
    public static void main(String[] ar) {
        Scanner teclado=new Scanner(System.in);
        String nombre1,nombre2;
        int edad1,edad2;
        System.out.print("Ingrese el nombre:");
        nombre1=teclado.next();
        System.out.print("Ingrese edad:");
        edad1=teclado.nextInt();
        System.out.print("Ingrese el nombre:");
        nombre2=teclado.next();
        System.out.print("Ingrese edad:");
        edad2=teclado.nextInt();
        System.out.print("La persona de mayor edad es:");
        if (edad1>edad2) {
            System.out.print(nombre1);
        } else {
            System.out.print(nombre2);
        }
    }
2.-Se desea guardar los sueldos de 5 operarios.
Según lo conocido deberíamos definir 5 variables si queremos tener en un cierto momento los 5 sueldos almacenados en memoria.
Empleando un vector solo se requiere definir un único nombre y accedemos a cada elemento por medio del subíndice.

import java.util.Scanner;

public class PruebaVector1 {

    private Scanner teclado;

    private int[] sueldos;

    public void cargar()
    {
        teclado=new Scanner(System.in);
        sueldos=new int[5];
        for(int f=0;f<5;f++) {
            System.out.print("Ingrese sueldo:");
            sueldos[f]=teclado.nextInt();
        }
    }
    public void imprimir() {
        for(int f=0;f<5;f++) {
            System.out.println(sueldos[f]);
        }
    }
    public static void main(String[] ar) {
        PruebaVector1 pv=new PruebaVector1();
        pv.cargar();
        pv.imprimir();
    }
}
Realizar un programa en lenguaje java que defina  un vector de tamaño 5 componentes de tipo float que representen las alturas de 5 personas.
Obtener el promedio de las mismas. Contar cuántas personas son más altas que el promedio y cuántas más bajas.
import java.util.Scanner;
public class Alturas {
    private Scanner teclado;
    private float[]Alturas; float Altura=0,Prom;int MA=0,MB=0;
    public void cargar(){
        teclado=new Scanner(System.in);
        Alturas=new float[5];
        for (int i=0;i<5;i=i+1){
            System.out.print("Ingrese la altura:");
            Alturas[i]=teclado.nextFloat();
           
                    Altura= Altura+Alturas[i];
        }
    }
    public void promedio(){
        Prom=Altura/5;
        System.out.print("El promedio de las alturas es:");
        System.out.println(Prom);
    }
    public void mayormenor(){
        for (int i=0;i<5;i=i+1){
            if (Alturas[i]>Prom){
                MA=MA+1;               
            }
            else {
                MB=MB+1;
            }
        }
    System.out.print("La cantidad de personas mas altas que el promedio es:");
    System.out.println(MA);
    System.out.print("La cantidad de pesonas mas bajas que el promedio es:");
    System.out.println(MB);
    }
    public static void main(String[]ar){
        Alturas   a=new   Alturas();
        a.cargar();
        a.promedio();
        a.mayormenor();
    }
}
Una empresa tiene dos turnos deonde trabajan 8 empleados, 4 en la mañana y 4 en la tarde. Realizar un programa que permita almacenar los sueldos de los empleados por turno y que imprima el gasto total de sueldos por turnos.
import java.util.Scanner;
public class Empresa {
    private Scanner teclado;
    private float[]EmpleadosM;float SM=0,ST=0;int x;
    private float[]EmpleadosT;
    public void cargar(){
        teclado=new Scanner(System.in);
        EmpleadosM=new float[4];
        EmpleadosT=new float[4];
       for(int y=0;y<2;y++){
        System.out.print("Ingrese el numero 1 si pertenece al turno matutino o el numero 2 si pertenece al vespertino:");
        x=teclado.nextInt();
        if (x<2){
        for(int f=0;f<4;f=f+1){
            System.out.print("Ingrese el sueldo del empleado  de la mañana:");
            EmpleadosM[f]=teclado.nextFloat();
            SM=SM+EmpleadosM[f];
           
        }
    }
        else{
            for(int f=0;f<4;f++){
           System.out.print("Ingrese el sueldo del empleado  de la tarde:");
           EmpleadosT[f]=teclado.nextFloat();
            ST=ST+EmpleadosT[f];
            }
        }}}
    public void imprimir(){
        System.out.println("El Gasto en sueldos de la mañana es:"+SM);
        System.out.println("El Gasto en sueldos de la tarde es:"+ST);
    }
    public static void main(String[]ar){
        Empresa      e=new             Empresa();
        e.cargar();
        e.imprimir();
    }

}
Se tienen las calificaciones del primer parcial de los 2 materias, las materias A y B cada materia cuenta con 5 alumnos. Realizar un programa que muestre la materia que obtuvo el mayor promedio general.

import java.util.Scanner;
public class Materias {
    private Scanner teclado;
    private float[]A;
    private float[]B;
    float CTB=0,CTA=0,PromA,PromB;
    public void cargar(){
        teclado=new Scanner(System.in);
        A=new float[5];
        B=new float[5];
        for(int f=0;f<5;f++){
            System.out.print("Ingrese la calificacion de la clase A:");
            A[f]=teclado.nextFloat();
            System.out.print("Ingrese la calificacion de la clase B:");
            B[f]=teclado.nextFloat();
            CTA=CTA+A[f];
            CTB=CTB+B[f];            
        }    }
    public void promediomayor(){
        PromA=CTA/5;
        PromB=CTB/5;
        if(PromA>PromB){
            System.out.println("La materia con mayor promedio es la A:"+PromA);
        }
        else{
            System.out.println("La materia con mayor promedio es la B:"+PromB);
        }
    }
    public static void main(String[]ar){
        Materias           m=new          Materias();
        m.cargar();
        m.promediomayor();
    }
}
Formularios


1.-

package vocalesjamc;
import java.awt.BorderLayout ;
/**
 * @author AlejandroMireles
 */
public class ContadorDeVocales extends javax.swing.JFrame {
void Aceptar(){
    String texto;
    int x;
    texto=txtcuenta.getText();
    int cuentavocales=0;
    for (x=0;x<texto.length();x++){
        if ((texto.charAt(x)=='a')||
            (texto.charAt(x)=='e')||
            (texto.charAt(x)=='i')||
            (texto.charAt(x)=='o')||
            (texto.charAt(x)=='u')){
        cuentavocales++;
        }
    }
lblrespuesta.setText("El texto " + " " +texto+ " contiene " + cuentavocales + " vocales");
}

    void limpiar(){   
        txtcuenta.setText("");
        lblrespuesta.setText("");
    }
    
    public ContadorDeVocales(){ 
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btnAceptar = new javax.swing.JButton();
        btnNuevo = new javax.swing.JButton();
        txtcuenta = new javax.swing.JTextField();
        lblrespuesta = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(153, 153, 153));

        jLabel1.setFont(new java.awt.Font("Tahoma", 3, 24)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 102, 102));
        jLabel1.setText("CONTADOR DE VOCALES");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel2.setText("Ingrese texto");

        btnAceptar.setText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnNuevo.setText("Nuevo");
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        lblrespuesta.setForeground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnAceptar)
                        .addGap(26, 26, 26)
                        .addComponent(btnNuevo)
                        .addGap(67, 67, 67))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(103, 103, 103))))
            .addGroup(layout.createSequentialGroup()
                .addGap(42, 42, 42)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblrespuesta, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(txtcuenta, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 44, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtcuenta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAceptar)
                    .addComponent(btnNuevo))
                .addGap(18, 18, 18)
                .addComponent(lblrespuesta, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(36, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        
private void formWindowOpened(java.awt.event.WindowEvent evt){
    FondoFormulario AplicarFondo=new FondoFormulario();
    this.add(AplicarFondo , BorderLayout.SOUTH);
    AplicarFondo.repaint();}
    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        Aceptar();
    }                                          

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        limpiar();
    }                                        
    /**
     * @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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ContadorDeVocales.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ContadorDeVocales().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel lblrespuesta;
    private javax.swing.JTextField txtcuenta;
    // End of variables declaration                   
}
2.-


package carrerasjamc;

public class Carreras extends javax.swing.JFrame {
void Carreras(){
String msj=("Carreras elegidas:");
if (chkderecho.isSelected()){
    msj=msj+", Derecho";
}
if (chksistemas.isSelected()){
    msj=msj+", Sistemas";
}
if (chkconta.isSelected()){
    msj=msj+", Contabilidad";
}
if (chkeco.isSelected()){
    msj=msj+", Economia";
}
lblrespuesta.setText(msj);
}
void limpiar(){
    lblrespuesta.setText("");
    if(chkderecho.isSelected()){
        chkderecho.setSelected(false);
    }
    if(chksistemas.isSelected()){
        chksistemas.setSelected(false);
    }
    if(chkconta.isSelected()){
        chkconta.setSelected(false);
    }
    if(chkeco.isSelected()){
        chkeco.setSelected(false);
    }
}
    public Carreras() {
        initComponents();
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        chkderecho = new javax.swing.JCheckBox();
        chksistemas = new javax.swing.JCheckBox();
        chkconta = new javax.swing.JCheckBox();
        chkeco = new javax.swing.JCheckBox();
        btnaceptar = new javax.swing.JButton();
        btnnuevo = new javax.swing.JButton();
        lblrespuesta = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Times New Roman", 3, 36)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 102, 51));
        jLabel1.setText("                   Eleccion de Carreras");

        chkderecho.setText("Derecho");
        chkderecho.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkderechoActionPerformed(evt);
            }
        });

        chksistemas.setText("Sistemas");
        chksistemas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chksistemasActionPerformed(evt);
            }
        });

        chkconta.setText("Contabilidad");
        chkconta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkcontaActionPerformed(evt);
            }
        });

        chkeco.setText("Economia");
        chkeco.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkecoActionPerformed(evt);
            }
        });

        btnaceptar.setText("Aceptar");
        btnaceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnaceptarActionPerformed(evt);
            }
        });

        btnnuevo.setText("Nuevo");
        btnnuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnnuevoActionPerformed(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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(74, 74, 74)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(chkconta)
                                    .addComponent(chkeco)
                                    .addComponent(chksistemas)
                                    .addComponent(chkderecho)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(127, 127, 127)
                                .addComponent(btnaceptar)
                                .addGap(141, 141, 141)
                                .addComponent(btnnuevo)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(65, 65, 65)
                .addComponent(lblrespuesta, javax.swing.GroupLayout.PREFERRED_SIZE, 515, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(106, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(39, 39, 39)
                .addComponent(chkderecho)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(chksistemas)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(chkconta)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(chkeco)
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnaceptar)
                    .addComponent(btnnuevo))
                .addGap(61, 61, 61)
                .addComponent(lblrespuesta, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(92, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void chkderechoActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                          

    private void btnaceptarActionPerformed(java.awt.event.ActionEvent evt) {                                           
     Carreras();   // TODO add your handling code here:
    }                                          

    private void btnnuevoActionPerformed(java.awt.event.ActionEvent evt) {                                         
      limpiar();  // TODO add your handling code here:
    }                                        

    private void chksistemasActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void chkcontaActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void chkecoActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
    }                                      

    /**
     * @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(Carreras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Carreras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Carreras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Carreras.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 Carreras().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton btnaceptar;
    private javax.swing.JButton btnnuevo;
    private javax.swing.JCheckBox chkconta;
    private javax.swing.JCheckBox chkderecho;
    private javax.swing.JCheckBox chkeco;
    private javax.swing.JCheckBox chksistemas;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel lblrespuesta;
    // End of variables declaration                   
}


viernes, 31 de octubre de 2014

Los arreglos en Java



¿Cuál es la diferencia entre las variables y los datos?
 La diferencia que encontramos es que el dato siempre va a hacer el mismo, mientras que la variable como su nombre lo indica puede cambiar.

¿Qué significa ámbito o alcance de una variable?
 El ámbito de una variable es la zona del programa en la que se define la variable. JavaScript define dos ámbitos para las variables global y local.

Menciona los diferentes tipos de arreglos
  • ·         Arreglo subdimensional: es un tipo de dato estructurado que está formado de una colección finita y ordenada de datos del mismo tipo.
  • ·         Arreglo bidimensional: es un tipo de dato estructurado, finito y ordenado es en forma directa por medio de un par de índices.
  • ·         Arreglo multidimensional: está compuesto por n dimensiones, es necesario utilizar n índices, uno por cada dimensión.


¿Cuáles son los dos métodos para crear un arreglo?
new array(longitud matris)
new arry(elemento o,elemento...elemento n)
matriz literal
[elemento o,elemento1...,elemento n]


¿Qué es una constante?
 Es un valor que no puede ser alterado durante la ejecución de un programa. Una constante corresponde a una longitud fija de un área reservada en la memoria principal del ordenador donde el programa almacena valores fijos.

¿Para qué se utilizan los comentarios en java y como se definen?
Son líneas de texto insertadas en el programa para documentarlo y facilitar su lectura.