lunes, 28 de julio de 2014

llenar matriz NxN aleatoriamente e introducir cuantos elementos a intercambiar e introducirlos e imprimir la matriz con elementos nuevos

Números aleatorios del 1 al 9  llenar una matriz bidimencional que pida el tamaño de la matriz a llenar de (N números) Nfilas x Ncolumnas y que una vez llena la matriz con números aleatorios pida cuantos números se van a cambiar e introducirlos, e imprimir la matriz cada vez que se cambien los valores.





Primero creamos la clase  Mat.java que va hacer la matriz bidimensional, y tendrá el  método  para imprimir 

public class Mat{
public int Mat [][];
public int filas, columnas;
public Mat(){
}
public Mat(int f, int c){
filas=f;
columnas=c;
Mat=new int [filas][columnas];
}
public void Llenar(int valor, int i, int j){
Mat[i][j]=valor;
}
public void Mostrar(){ // Muestra los elementos de la matriz. 
System.out.println("Matriz:"); 
for(int i=0;i<filas;i++){ 
for(int j=0;j<columnas;j++){ 
System.out.print(Mat[i][j]+" "); 
System.out.println(); 
}
}

Creamos la clase Sod.java  que sera la clase principal
import java.util.Scanner;
import java.util.Random;
import javax.swing.JOptionPane;

public class Sod{
public static void main(String[] arg){ 
Mat A;
int a,b,c, numeroaleatorio;
Scanner teclado=new Scanner(System.in);
Random  aleatorio = new Random(); 


System.out.println("datos de matriz ");

System.out.println ("filas");
 a=teclado.nextInt();
System.out.println ("columnas");
 b=teclado.nextInt();
 System.out.println ();
 A=new Mat(a,b);
 for(int i=0;i<A.filas;i++){ 
for(int j=0;j<A.columnas;j++){ 
  numeroaleatorio=(int)Math.floor(Math.random()*(9-1+1)+1);
  // (int)(Math.random()*(HASTA-DESDE+1)+DESDE);
 A.Llenar(numeroaleatorio, i, j);
}

 A.Mostrar();
  System.out.println ("cuantos numeros de la matriz va a cambiar");
    int ii=0, cargador=0; 
   ii=teclado.nextInt();
do{
  System.out.println ("ingresar valor del numero a cambiar");
  int i =teclado.nextInt();
 System.out.println ("en fila");
 int o =teclado.nextInt();
 System.out.println ("en columna");
int u =teclado.nextInt();
 A.Llenar(i,o , u);
 A.Mostrar();

    cargador=cargador+1;
 } while (cargador<=ii);
 
    
}

}


Corrida del programa


--------------------Configuration: <Default>--------------------
datos de matriz 

filas
4
columnas
4

Matriz:
8 6 7 9 
1 6 8 1 
8 7 2 2 
9 8 3 1 
cuantos numeros de la matriz va a cambiar
2
ingresar valor del numero a cambiar
3
en fila
1
en columna
3
Matriz:
8 6 7 9 
1 6 8 3 
8 7 2 2 
9 8 3 1 
ingresar valor del numero a cambiar
3
en fila
3
en columna
2
Matriz:
8 6 7 9 
1 6 8 3 
8 7 2 2 
9 8 3 1 
ingresar valor del numero a cambiar
1
en fila
1
en columna
1
Matriz:
8 6 7 9 
1 1 8 3 
8 7 2 2 
9 8 3 1 

Process completed.


miércoles, 23 de julio de 2014

Hacer un programa en java por medio de una interfaz grafica un menú que incluya nuevo, guardar, y eliminar un cliente de una base de datos, la interfaz debe contener botones y cajas de texto para introducir la información como su nombre, dirección y teléfono, y en el menú debe a ver una opción de salir.

Hacer un programa en java por medio de una interfaz grafica un menú que incluya nuevo, guardar, y eliminar un cliente de una base de datos, la interfaz debe contener botones y cajas de texto para introducir la información como su nombre, dirección y teléfono, y en el menú debe a ver una opción de salir.
Necesitamos tener instalado MySQL en  este link como instalarlo





Primero hacemos la base de datos en mysql:

CREATE DATABASE cliente; creamos la base de datos
USE cliente;             usamos esa base de datos
CREATE TABLE `cliente` (           creamos las tablas a usar para la base de datos
  `nombre` varchar(30) default NULL,
  `direccion` varchar(50) default NULL,
  `telefono` varchar(20) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `cliente` (`nombre`,`direccion`,`telefono`) VALUES     insertamos los datos en la tabla cliente
 ('Manuel','salinas 203','12345677');

Despues descargas mysql-connector-java  y lo pones en  C:\Program Files\Java\jdk1.6.0_22\jre\lib\ext  esto es muy importante o lo guardas en la carpeta del proyecto este conector es un archivo .jar

después creamos un archivo con el nombre cliente (cliente.java) en jcreator



import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.*;

public class cliente extends JFrame

{             
                public static String url="jdbc:mysql://localhost:3307/cliente?user=root&password=";
                 JLabel l1, l2, l3;
                public static JTextField txt1, txt2, txt3;
                 public static JButton b1, b2, b3;
                 JPanel contentPane;
               
                               JMenuBar menu;
                    JMenu archivo, administrar;
                    JMenuItem salir, nuevo, guardar, Eliminar;
                  
                   
                public cliente() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException
                {                             
                               super();
                               Inicializar();
                              
                               this.setVisible(true);
                }

                private void Inicializar() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException
                {
                                                              
                                               menu = new JMenuBar();
                        archivo = new JMenu("Archivo");
                        administrar = new JMenu("Administrar");
                        salir = new JMenuItem("Salir");
                        nuevo = new JMenuItem("Nuevo");
                        guardar         = new JMenuItem("Guardar");
                        Eliminar = new JMenuItem("Eliminar");
                        archivo.add(salir);
                        administrar.add(nuevo);
                        administrar.add(guardar          );
                        administrar.add(Eliminar);
                        menu.add(archivo);
                        menu.add(administrar);
                       
                       
                       
                               l1 = new JLabel();
                               l2 = new JLabel();
                               l3 = new JLabel();
                               txt1 = new JTextField();
                               txt2 = new JTextField();
                               txt3 = new JTextField();
                               b1 = new JButton();
                               b2 = new JButton();
                               b3 = new JButton();
                               contentPane = (JPanel)this.getContentPane();

                               l1.setBackground(new Color(0, 170, 255));
                               l1.setHorizontalAlignment(SwingConstants.CENTER);
                               l1.setHorizontalTextPosition(SwingConstants.CENTER);
                               l1.setText("Nombre");
                              
                               l2.setBackground(new Color(0, 170, 255));
                               l2.setHorizontalAlignment(SwingConstants.CENTER);
                               l2.setText("Dirección");
                              
                               l3.setHorizontalAlignment(SwingConstants.CENTER);
                               l3.setText("Telefono");
                              
                              
                               b1.setText("Nuevo");
                               b1.addActionListener(new ActionListener() {
                                               public void actionPerformed(ActionEvent e)
                                               {
                                                               limpiar();
                                                              
                                               }

                               });
                              
                                                              
                                b2.setText("Guardar");
                               b2.addActionListener(new ActionListener() {
                                               public void actionPerformed(ActionEvent e)
                                               {
                                                               guardar();
                                                              
                                               }
                               });
                              
                              
                               b3.setText("Eliminar");
                               b3.addActionListener(new ActionListener() {
                                               public void actionPerformed(ActionEvent e)
                                              
                                               {
                                                               eliminar();
                               }
                                              
                                              
                               });
                              
                               nuevo.addActionListener(new ActionListener() {
                                               public void actionPerformed(ActionEvent e)
                                               {
                                                               limpiar();
                                                              
                                               }

                               });
                              
               
                                                              
                               guardar.addActionListener(new ActionListener() {
                                               public void actionPerformed(ActionEvent e)
                                               {
                                                               guardar();
                                                              
                                               }
                               });
                              
                              
                              
                               Eliminar.addActionListener(new ActionListener() {
                                               public void actionPerformed(ActionEvent e)
                                              
                                               {
                                                               eliminar();
                               }
                                              
                                              
                               });
                              
                              
                               salir.addActionListener(new ActionListener() {
                                               public void actionPerformed(ActionEvent e)
                                              
                                               {
                                                               System.exit(0);
                               }
                                              
                                              
                               });
                              
                               contentPane.setLayout(null);
                               addComponent(contentPane, l1, 41,70,60,28);
                               addComponent(contentPane, l2, 42,108,60,22);
                               addComponent(contentPane, l3, 39,148,60,18);
                               addComponent(contentPane, txt1, 110,76,100,22);
                               addComponent(contentPane, txt2, 110,111,100,22);
                               addComponent(contentPane, txt3, 110,148,100,22);
                               addComponent(contentPane, b1, 251,70,108,28);
                               addComponent(contentPane, b2, 251,107,108,28);
                               addComponent(contentPane, b3, 251,144,108,28);
                               addComponent(contentPane, menu, 0,1,700,28);
                              
                               this.setTitle("Nuevo Cliente");
                               this.setLocation(new Point(235, 195));
                               this.setSize(new Dimension(446, 244));
                               this.setResizable(false);
                              
                              
                }
private void addComponent(Container container,Component c,int x,int y,int width,int height)
                {
                               c.setBounds(x,y,width,height);
                               container.add(c);
                }

                public static void main(String[] args) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException
                {
                               new cliente();
                              
                              
                }
                private static void limpiar() {
                               txt1.setText("");
                               txt2.setText("");
                               txt3.setText("");
                              
                }

                private static void eliminar() {
                               try
                               {
                                               Class.forName("com.mysql.jdbc.Driver").newInstance();
                                               Connection con=DriverManager.getConnection(url);
                                               Statement st=con.createStatement();
                                               String query="delete from cliente where nombre='"+txt1.getText()+"'";
                                               int n=st.executeUpdate(query);
                                               con.close();
                               }catch (SQLException e2) {
                                              
                                               e2.printStackTrace();
                               } catch (InstantiationException e2) {
                                               // TODO Auto-generated catch block
                                               e2.printStackTrace();
                               } catch (IllegalAccessException e2) {
                                               // TODO Auto-generated catch block
                                               e2.printStackTrace();
                               } catch (ClassNotFoundException e2) {
                                               // TODO Auto-generated catch block
                                               e2.printStackTrace();
                               }
                               JOptionPane.showMessageDialog(null, "Se elimino el registro "+txt1.getText());
                               txt1.setText("");
                              
                }

                private static void guardar() {
                               try{                                                                                                                                     
                                              
                                               Class.forName("com.mysql.jdbc.Driver").newInstance();                                     
                                               Connection con=DriverManager.getConnection(url);
                                               Statement st=con.createStatement();
                                               String query="insert into cliente values ('"+ txt1.getText() +"','"+txt2.getText()+"','"+txt3.getText()+"')";
                                               int n=st.executeUpdate(query);
                                               con.close();
                               }catch (SQLException e1) {
                                              
                                               e1.printStackTrace();
                               } catch (InstantiationException e1) {
                                               // TODO Auto-generated catch block
                                               e1.printStackTrace();
                               } catch (IllegalAccessException e1) {
                                               // TODO Auto-generated catch block
                                               e1.printStackTrace();
                               } catch (ClassNotFoundException e1) {
                                               // TODO Auto-generated catch block
                                               e1.printStackTrace();
                               }
                               JOptionPane.showMessageDialog(null, "Se Guardo el registro ");
                limpiar();
                              
                }
               

                }